0
votes

I have an image to be drawn on an html5 canvas. I want to resize this image to a certain height and width before being drawn onto the canvas. My code currently consists of:

img = new Image();
img.src = "vivo.jpg";

// calcuate new height and width

img.height = newheight;
img.width = newwidth;
$("#cnvs").attr({
    "height" : newheight,
    "width" : newwidth
    });
context.drawImage(img, 0, 0);

The code only works if I include the width and height parameters in the context.drawImage() function itself. But what I don't understand is, why the image isn't resized already before the context.drawImage() function accesses it.

I have also printed alert statements to check "img.height" and "img.width" and it is indeed set to the values of newheight, newwidth. Why would the context.drawImage() access the old values of height and width?

Edit - Additionally, when I display the image on the webpage (not on the canvas, but just the webpage), the resized image is shown. But the canvas does not show the resized image. I don't understand why

1

1 Answers

1
votes

The reason why it isn't working is because you are changing the properties of the <img> HTML node. These properties are layouting instructions how the node is displayed in the document (which are obsolete, by the way. Use CSS for layouting). The width and height of the image material displayed in the image-element is independent from this.