Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

javascript - How to proportionally resize an image in canvas?

AFAIK, to resize a loaded image in HTML5 canvas would be done like this:

var img = new Image();
img.onload = function () {
  ctx.drawImage(img, 0, 0, 300, 200); // resizes image to 300px wide, 200px high
}
img.src = 'images/myimage.jpg';

But then I realised that the image wouldn't be proportionally correct. So then I tried using one parameter only (just like in HTML) but I found that didn't work either.

How do I proportionally resize the image?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Get the img.width and img.height, then calculate the proportional height according to what width you're sizing to.

For example:

ctx.drawImage(img, 300, 0, 300, img.height * (300/img.width));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...