Shane
Shane

Reputation: 1230

What units does canvas.drawImage() use when specifying position and dimensions?

I have a canvas with a percentage width and height, and I am drawing an image in there.

I would like to draw the image with 50% width, and 100% height of the canvas. How do I accomplish this?

Here's some code:

#canvas {
     width: 100%;
     height: 33%;
}

var cv = document.getElementById('canvas');
var cx = cv.getContext('2d');

var bg = document.createElement('img');
bg.src = bg_url;

cx.drawImage(bg, ?, ?, ?, ?);
// cx.drawImage(bg, 0, 0, 50%, 100%); essentially

// now let's draw that second image at 50% of the canvas (tiling)

cx.drawImage(bg, ?, ?, ?, ?);
// cx.drawImage(bg, 50%, 0, 50%, 100%); essentially

Upvotes: 1

Views: 5046

Answers (1)

user1693593
user1693593

Reputation:

What units does canvas.drawImage() use when specifying position and dimensions?

It uses CSS pixels for all its dimensions.

This:

#canvas {
     width: 100%;
     height: 33%;
}

will just scale the canvas as an image. The canvas pixel dimension will remain the same just resulting in a lower quality result. As a thum-of-rule always set absolute size on the canvas element (if you don't the size will always be 300 x 150 pixels no matter what you set with CSS).

var canvas = document.getElementById('canvasID');

canvas.width = window.innerWidth;        // use the target size instead if
canvas.height = window.innerHeight * 33; // not the window

And then:

cx.drawImage(bg, 0, 0, canvas.width * 0.5, canvas.height);

Upvotes: 1

Related Questions