Javascript 画布 drawImage 缩放
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10841532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Canvas drawImage scaling
提问by selanac82
I'm trying to scale an image proportionately to the canvas. I'm able to scale it with fixed width and height as so:
我正在尝试将图像按比例缩放到画布。我可以用固定的宽度和高度缩放它,如下所示:
context.drawImage(imageObj, 0, 0, 100, 100)
But I only want to resize the width and have the height resize proportionately. Something like the following:
但我只想调整宽度并按比例调整高度。类似于以下内容:
context.drawImage(imageObj, 0, 0, 100, auto)
I've looked everywhere I can think of and haven't seen if this is possible.
我找遍了所有我能想到的地方,但还没有看到这是否可能。
回答by Gaurav
context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)
回答by Mashhood
solution of @TechMaze is quite good.
@TechMaze 的解决方案非常好。
here is the code after some correctness and introduction of image.onload event. image.onloadis too much essential in order to abstain from any kind of distortion.
这是经过一些正确性和引入 image.onload 事件后的代码。image.onload对于避免任何类型的失真来说太重要了。
function draw_canvas_image() {
var canvas = document.getElementById("image-holder-canvas");
var context = canvas.getContext("2d");
var imageObj = document.getElementById("myImageToDisplayOnCanvas");
imageObj.onload = function() {
var imgWidth = imageObj.naturalWidth;
var screenWidth = canvas.width;
var scaleX = 1;
if (imgWidth > screenWidth)
scaleX = screenWidth/imgWidth;
var imgHeight = imageObj.naturalHeight;
var screenHeight = canvas.height;
var scaleY = 1;
if (imgHeight > screenHeight)
scaleY = screenHeight/imgHeight;
var scale = scaleY;
if(scaleX < scaleY)
scale = scaleX;
if(scale < 1){
imgHeight = imgHeight*scale;
imgWidth = imgWidth*scale;
}
canvas.height = imgHeight;
canvas.width = imgWidth;
context.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);
}
}
回答by TechMaze
And if you want to properly scale the picture as per screen size, here is the math you can do: IF YOU ARE NOT USING JQUERY, REPLACE $(window).width with appropriate equivalent option.
如果您想根据屏幕尺寸正确缩放图片,您可以执行以下数学运算:如果您不使用 JQUERY,请使用适当的等效选项替换 $(window).width。
var imgWidth = imageObj.naturalWidth;
var screenWidth = $(window).width() - 20;
var scaleX = 1;
if (imageWdith > screenWdith)
scaleX = screenWidth/imgWidth;
var imgHeight = imageObj.naturalHeight;
var screenHeight = $(window).height() - canvas.offsetTop-10;
var scaleY = 1;
if (imgHeight > screenHeight)
scaleY = screenHeight/imgHeight;
var scale = scaleY;
if(scaleX < scaleY)
scale = scaleX;
if(scale < 1){
imgHeight = imgHeight*scale;
imgWidth = imgWidth*scale;
}
canvas.height = imgHeight;
canvas.width = imgWidth;
ctx.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);