Question

I'm trying to draw an image onto a canvas, like this:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,0,0,100,100,0,0,200,200);

The canvas is 200px by 200px and the image is much bigger (but styled at 200px by 200px too)

As you can see in the jsfiddle the canvas doesn't show the image (I was expecting a part of the image). My understanding of drawImage (as is described here) goes like this:

  • "0,0,100,100" defines a rectangle on the image which is the part that is drawn onto the canvas. 0,0 defines the top/left corner and 100,100 are the widths of the sides.
  • This rectangle is drawn onto the canvas inside the rectangle defined by 0,0,200,200

Any suggestions what goes wrong here ?

Was it helpful?

Solution

You image is actually 585 x 585 so what you are doing is to clip a corner from it (which is blank) and draw it onto canvas which of course won't show anything.

Scaling the image with CSS doesn't actually change its size. It only scales it for display.

So what you need to do is to use the original size of the image as basis. If you simply want to scale it down to fit in canvas you can do:

ctx.drawImage(img, 0, 0, 200, 200);

The same goes for canvas. Don't scale canvas using CSS but set the width and height properties/attributes or else the canvas will default to 300x150 (which is then scaled by your css):

<canvas width=200 height=200 ...>

Modified fiddle

OTHER TIPS

Set the width and height on the canvas and draw the image at the same dimensions. Updated your fiddle - http://jsfiddle.net/FQhGg/2/

var c=document.getElementById("myCanvas"),
    ctx=c.getContext("2d"),
    img=document.getElementById("scream"),
    width = img.width,
    height = img.height;

c.width = width;
c.height = height;
ctx.drawImage(img,0,0,width,height);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top