66

我正在尝试将图像按比例缩放到画布上。我可以用固定的宽度和高度来缩放它,如下所示:

context.drawImage(imageObj, 0, 0, 100, 100)

但我只想调整宽度并按比例调整高度。类似于以下内容:

context.drawImage(imageObj, 0, 0, 100, auto)

我到处寻找我能想到的地方,但还没有看到这是否可能。

4

3 回答 3

109
context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)
于 2012-05-31T22:54:55.563 回答
9

@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);
  }
}
于 2016-08-04T16:41:54.987 回答
1

如果您想根据屏幕尺寸正确缩放图片,可以使用以下代码:

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);

如果您不使用 jQuery,请替换$(window).width为适当的等效选项。

于 2015-09-04T18:11:49.797 回答