Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using canvas to draw image at true size

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.net/KdrYr/1/

var img = new Image();
var cv = document.getElementById('thecanvas');
img.src = 'http://www.photographyblogger.net/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 :/)

Expected Image

But end up with this

Actual image

What could be causing this?

like image 489
KJ Tsanaktsidis Avatar asked Oct 13 '13 11:10

KJ Tsanaktsidis


People also ask

How do you make a full picture on canvas?

The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.

How do I change the height and width of an image in canvas?

To set the height and width canvas HTML5 has two attributes: Height: With the help of Height attribute we can set the height. Width: With the help of Width attribute we can set the width.

How do I change the width and height of a dynamic canvas?

To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas . height = 500 ; drawScreen ();


1 Answers

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.

like image 91
Shadow Wizard Hates Omicron Avatar answered Oct 17 '22 10:10

Shadow Wizard Hates Omicron