I'm rendering an image to a canvas. After reading the drawImage MDN API, it looks like the following two lines of code should produce the same result:
var ctx = canvas.getContext('2d');
ctx.drawImage(this.image, 0, 0, this.image.width, this.image.height, 0, 0, this.clip.width, this.clip.height);
ctx.drawImage(this.image, 0, 0, this.clip.width, this.clip.height);
But they DON'T! and I can't figure out why. The first one scales the image to fill up this.clip
, which is what I expect. But the second doesn't seem to scale to mater what this.clip
is, and the image seems to go outside of its own bounds.
Now, this is an image I generated in javascript, so is there any way I could have screwed up the image creation such that this would happen?
If it helps. This below is the code I use to make the image.
this.image = new Image(this.getSize()[0],this.getSize()[1]);
//this.getSize() = [32, 42, 40];
var c = document.createElement('canvas');
var ctx = c.getContext('2d');
var pixels = ctx.createImageData(this.image.width, this.image.height);
for (var x = 0; x < this.image.width; x++) {
for (var y = 0; y < this.image.height; y++) {
var i = (x + y*this.image.width)*4;
var color = scalarToHue(this.sample(x,y,layer),0,10,50);
pixels.data[i] = Math.round(color[0]*255);
pixels.data[i + 1] = Math.round(color[1]*255);
pixels.data[i + 2] = Math.round(color[2]*255);
pixels.data[i + 3] = 255;
}
}
ctx.putImageData(pixels, 0, 0);
this.image.src = c.toDataURL("image.png");
Also, I'm using chrome.
This is because you are hard-coding your image
's width and height properties by setting it in the Image(width, height)
constructor.
ctx.drawImage(img, dx, dy [, dwidth ,dheight])
will make swidth
and sheight
default to your image's naturalWidth
and naturalHeight
, not to their width
and height
ones.
So in your code, this means that the first line will use 32 and 42 as values for swidth and sheight, while the second line will use 300 and 150 if I read your code correctly.
Ps: re-reading your code, it seems that all you want is to set your canvas's width and height to these values before drawing on it, then you'll just need the drawImage(x, y)
version.