1

I've seen in all canvas image creating documentation (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images) that the new image constructor, e.g. myImg = new Image();, is used just like that with no parameters. However, I know that it takes optional parameters for width and height, e.g. myImg = new Image(400,300);.

Is it good practice to specify those parameters if you know the width and height of the image beforehand?

After the constructor I use myImg.src = 'myurl.jpg'; and myImg.onload = function() { ctx.drawImage(myImg, x, y)...};

0

1 Answer 1

2

If you're going to draw the new image to the canvas, then there's no need to specify the image size in the image's constructor. Javascript will know the image's native size after the image is fully loaded in myImg.onload.

When you draw the image on the canvas using context.drawImage, by default the image will be drawn at its native size. But you can also specify a different image size with extra arguments to drawImage:

// draw myImg on the canvas in the top-left corner
// and resize the image to half-size
context.drawImage(myImg, 0,0, myImg.width/2, myImg.height/2);

If you want the canvas to be the same size as your image, you must resize the canvas inside your myImg.onload which is the first time javascript knows the native size of the image:

// create the canvas element its context
var canvas=document.createElement('canvas');
var context=canvas.getContext('2d');

// create the image object
var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){

    // The native image size is now known,
    // so resize the canvas to the same size as the image
    canvas.width=img.width;
    canvas.height=img.height;

    // draw the image on the canvas
    context.drawImage(img,0,0);
}
1
  • 1
    Great! Thanks for clarifying why it should be done this way and adding additional points. Feb 12, 2015 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.