I'm trying to resize a <canvas>
with an image already drawn, but I'm misunderstanding how to use the canvas.scale()
method because it doesn't shrink...
Code:
ImageRender.prototype.resizeTo = function () {
var canvas = $('#myCanvas')[0];
var ctx = canvas.getContext("2d");
//current image
var currImg = ctx.getImageData(0, 0, canvas.width, canvas.height);
//
var tempCanvas = $('canvas')[0];
var tempCtx = tempCanvas.getContext("2d");
tempCtx.putImageData(currImg, 0, 0)
//
ctx.scale(0.5, 0.5);
//redraw
ctx.drawImage(tempCanvas, 0, 0);
};
What am I overlooking?
Thanks!
You can scale your canvas with content by "bouncing" the content off a temporary canvas while you resize the original canvas. This save+redraw process is necessary because canvas content is automatically cleared when you resize the canvas width or height.
Example code:
var myCanvas=document.getElementById("canvas"); var ctx=myCanvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var tempCanvas=document.createElement("canvas"); var tctx=tempCanvas.getContext("2d"); var img=new Image(); img.crossOrigin='anonymous'; img.onload=start; img.src="https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg"; function start(){ myCanvas.width=img.width; myCanvas.height=img.height; ctx.drawImage(img,0,0); resizeTo(myCanvas,0.50); } function resizeTo(canvas,pct){ var cw=canvas.width; var ch=canvas.height; tempCanvas.width=cw; tempCanvas.height=ch; tctx.drawImage(canvas,0,0); canvas.width*=pct; canvas.height*=pct; var ctx=canvas.getContext('2d'); ctx.drawImage(tempCanvas,0,0,cw,ch,0,0,cw*pct,ch*pct); }
body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; }
<h4>Canvas resized to 50%</h4> <canvas id="canvas" width=300 height=300></canvas> <h4>Img with original image</h4> <img src='https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg'>
Simpler way would be using the extra parameters of drawImage()
. 4th and 5th parameters let you set the final width and height.
Also, you can paint an image (or a canvas) directly, without the need of getting the ImageData.
Also(2), I think you may want to resize the canvas too (just use its width and height properties)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.