我正在尝试根据画布按比例缩放图像。我可以用固定的宽度和高度缩放它,如下所示:
context.drawImage(imageObj, 0, 0, 100, 100)但我只想按比例调整宽度和高度。类似于以下内容:
context.drawImage(imageObj, 0, 0, 100, auto)我已经找遍了我能想到的所有地方,但还没有看到这是否可能。
发布于 2012-06-01 06:54:56
context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)发布于 2016-08-05 00:41:55
@TechMaze的解决方案非常好。
下面是在对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);
}
}发布于 2015-09-05 02:11:50
如果你想根据屏幕尺寸适当地缩放图片,下面是你可以做的数学运算:如果你没有使用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);https://stackoverflow.com/questions/10841532
复制相似问题