admin管理员组

文章数量:1302334

I'm trying to load an image from a URL into a HTML canvas at a 1:1 scale. I load the image, and set the canvas DOM element to the appropriate dimensions, but for some reason the image in the canvas is significantly upscaled and therefore only the top left hand corner is drawn.

This is demonstrated by the following JSFiddle: /

var img = new Image();
var cv = document.getElementById('thecanvas');
img.src = '.jpg';
img.onload = function() {
    var ctx = cv.getContext('2d');
    cv.style.width = img.width + 'px';
    cv.style.height = img.height + 'px';
    ctx.drawImage(img, 0, 0);
};

For example, I'm trying to draw this (sorry about the big images :/)

But end up with this

What could be causing this?

I'm trying to load an image from a URL into a HTML canvas at a 1:1 scale. I load the image, and set the canvas DOM element to the appropriate dimensions, but for some reason the image in the canvas is significantly upscaled and therefore only the top left hand corner is drawn.

This is demonstrated by the following JSFiddle: http://jsfiddle/KdrYr/1/

var img = new Image();
var cv = document.getElementById('thecanvas');
img.src = 'http://www.photographyblogger/wp-content/uploads/2009/12/Picture-in-a-picture4.jpg';
img.onload = function() {
    var ctx = cv.getContext('2d');
    cv.style.width = img.width + 'px';
    cv.style.height = img.height + 'px';
    ctx.drawImage(img, 0, 0);
};

For example, I'm trying to draw this (sorry about the big images :/)

But end up with this

What could be causing this?

Share asked Oct 13, 2013 at 11:58 KJ TsanaktsidisKJ Tsanaktsidis 1,2751 gold badge17 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You need to assign the canvas actual width and height, not via its style:

cv.width = img.width;
cv.height = img.height;

Live test case.

As for the why, well, it's explained already here.

本文标签: javascriptUsing canvas to draw image at true sizeStack Overflow