EarthUser EarthUser - 1 year ago 85
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() {
img.src= '';

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

Answer Source

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


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


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.


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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download