When rendering the following image (right-click + view image to see full size):
of size 4800x320 with html5 canvas.drawImage()
and trying to crop a partial 480x320 image from it, the canvas blows the image up.
Here is my code:
var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';
document.body.appendChild(canvas);
var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
var c=document.getElementById('my-canvas');
var ctx=c.getContext('2d');
ctx.drawImage(img,480,0,480,320,0,0,480,320);
}
also, when I draw the image to a smaller scale, it suddenly fits:
var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';
document.body.appendChild(canvas);
var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
var c=document.getElementById('my-canvas');
var ctx=c.getContext('2d');
ctx.drawImage(img,480,0,480,320,0,0,240,160);
}
does anyone knows why that is?
Canvas' default bitmap size is 300x150 pixels. Setting the CSS size won't change the bitmap size. The bitmap is set with its own width/height properties/attributes directly on the element. If not the bitmap will be stretched to fill the element CSS size.
Change these:
to
You can also setup your code to reuse the context: