Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling an image to fit on canvas

People also ask

How do you scale on canvas?

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.

How do I fit an image into a canvas in HTML?

The following code compares the ratios and chooses to fit the image horizontally or vertically. var canvas = document. getElementById('canvas'); var context = canvas. getContext('2d'); var imageObj = new Image(); var fitImageOn = function(canvas, imageObj) { var imageAspectRatio = imageObj.


You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output


Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas


I guess that you want the image to be scaled to a smaller size, without losing the ratio of the dimensions. I have a solution.

var ratio = image.naturalWidth / image.naturalHeight;
var width = canvas.width;
var height = width / ratio;
ctx.drawImage(image, 0, 0, width, height);

the ratio will be maintained. And the image drawn on the canvas will be of the same ratio. you can use the if loop if the height of the image is long, you can replace the canvas.width to some other width