【问题标题】:Canvas drawImage scaling画布绘制图像缩放
【发布时间】:2012-06-06 04:17:01
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript canvas html5-canvas resize drawimage


    【解决方案1】:
    context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)
    

    【讨论】:

    • 为了获得最佳性能,请确保您的图像以正确的宽度和高度保存并预加载。如果这是不可能的,您可以回退到下面的其他答案。
    【解决方案2】:

    如果您想根据屏幕尺寸正确缩放图片,您可以执行以下数学运算: 如果您没有使用 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);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-06
        • 2014-08-21
        相关资源
        最近更新 更多