EarthUser EarthUser - 1 month ago 11
Javascript Question

javascript canvas stretches my Image

$.fn.imageCanvas = function() {

if (!document.getElementById('bgCanvas')){
$('body').append($('<canvas>',{id:'bgCanvas', width:'500px', height: '500px'}))
var canvas = document.getElementById('bgCanvas');
var ctx = canvas.getContext('2d');
}
var img = new Image();
img.onload = function() {
ctx.drawImage(img,0,0,438,300);
console.log(this.width);
console.log(this.height);
}
img.src= 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}


In ctx.drawImage i wrote x,y,width,height. But canvas stretches this Image.
How can I image with original width/height

Answer

If you simply want to show the image without scaling, use the three-argument variant of drawImage with just x and y:

ctx.drawImage(img,0,0);

If you want to clip the bottom and right edge to your specified size, use the nine-argument variant:

ctx.drawImage(img,0,0,362,240,0,0,362,240);

The first four numbers set the x/y and width/height of the clipping rectangle, and the next four numbers set the x/y and width/height of the clipped image-rectangle that is drawn to the canvas.

EDIT:

The problem is that the jQuery function treats the width and height properties in the options object in the second argument as CSS properties, not as DOM object properties. If you inspect the HTML you generate, you'll find:

<canvas id="bgCanvas" style="width: 500px; height: 500px;"></canvas>

instead of what you want, which should be:

<canvas id="bgCanvas" width="500" height="500"></canvas>

See this question for a discussion about the problem. As a solution, I would suggest using instead:

$('body').append($('<canvas>',{id:"bgCanvas"}).attr({'width':500,'height':500}))
Comments