最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using canvas to draw image at true size - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论