Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  150] [ 4]  / answers: 1 / hits: 58888  / 11 Years ago, sat, february 22, 2014, 12:00:00

I'm drawing images on a canvas like this:


ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);

The picture is getting stretched and I don't want this. How can I simulate the CSS property?


background-size: cover

when drawing images on the canvas?


http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover


see the difference between 100% 100% (what I currently have) and cover (my goal).


More From » css

 Answers
17

It's a bit more complicated to get a cover functionality, though here is one solution for this:


Updated 2016-04-03 to address special cases. Also see @Yousef's comment below.


/**
* By Ken Fyrstenberg Nilsen
*
* drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
*
* If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {

if (arguments.length === 2) {
x = y = 0;
w = ctx.canvas.width;
h = ctx.canvas.height;
}

// default offset is center
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
offsetY = typeof offsetY === "number" ? offsetY : 0.5;

// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0;
if (offsetY < 0) offsetY = 0;
if (offsetX > 1) offsetX = 1;
if (offsetY > 1) offsetY = 1;

var iw = img.width,
ih = img.height,
r = Math.min(w / iw, h / ih),
nw = iw * r, // new prop. width
nh = ih * r, // new prop. height
cx, cy, cw, ch, ar = 1;

// decide which gap to fill
if (nw < w) ar = w / nw;
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated
nw *= ar;
nh *= ar;

// calc source rectangle
cw = iw / (nw / w);
ch = ih / (nh / h);

cx = (iw - cw) * offsetX;
cy = (ih - ch) * offsetY;

// make sure source rectangle is valid
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cw > iw) cw = iw;
if (ch > ih) ch = ih;

// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}

Now you can call it like this:


drawImageProp(ctx, image, 0, 0, width, height);

and it will scale the image proportionally to fit inside in that container.


Use the two last parameters to offset the image:


var offsetX = 0.5;   // center x
var offsetY = 0.5; // center y
drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);

[#72368] Friday, February 21, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
beatrices

Total Points: 745
Total Questions: 103
Total Answers: 105

Location: Guam
Member since Tue, Nov 29, 2022
2 Years ago
;