【问题标题】:Automatically Scaling Canvas to drawn image自动缩放画布以绘制图像
【发布时间】:2014-05-14 11:51:32
【问题描述】:

我正在使用以下 javascript 将图像绘制到画布上。

var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function () {
    ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
}

img.src = "images/testimg.jpg";

当我这样做时,我只能看到原始图像的一部分。谁能解释如何在画布上绘制整个原始图像,最好不指定原始照片的尺寸。

【问题讨论】:

    标签: html canvas size scale drawimage


    【解决方案1】:

    将画布的高度和宽度设置为图像的高度和宽度。

    var canvas = document.getElementById('canvasId');
    var ctx = canvas.getContext('2d');
    var img = document.createElement('IMG');
    
    
        canvas.height = ImgHeight;
        canvas.width = ImgWidth;
    
    
    img.onload = function () {
        ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
    }
    
    img.src = "images/testimg.jpg";
    

    【讨论】:

      【解决方案2】:

      这是@Ctrl Alt Design 答案的替代方法,它调整画布大小以适合图像。

      此示例缩放图像以适合画布,同时保持图像的纵横比:

      var img=new Image();
      img.onload=start;
      img.src="images/testimg.jpg";
      function start(){
      
          // calculate the scaling factor necessary
          // to fit the image in the exsiting canvas size
          // while maintaining the image's aspect ratio
      
          var scaleFactor=Math.min((canvas.width/img.width),(canvas.height/img.height));
      
          ctx.drawImage(img,0,0,img.width*scaleFactor,img.height*scaleFactor);
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多