【问题标题】:Prevent Image from Scaling Proportionally with HTML5 Canvas使用 HTML5 Canvas 防止图像按比例缩放
【发布时间】:2013-06-04 10:06:22
【问题描述】:

我希望能够在 HTML5 画布元素上绘制图像,其中图像的大小调整为画布宽度但不调整高度。本质上,我希望它将高度裁剪为画布高度,而不是尝试缩放宽度和高度。

例如,如果我在 320 x 150 的画布上绘制图像。我希望我的图像缩小到 320 的宽度并显示高度的前 150 像素。

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    你只需要计算图像的纵横比:

    var f = image.height / image.width;
    var newHeight = canvas.width * f;
    

    然后使用重新计算的图像高度绘制目的地:

    ctx.drawImage(image, 0, 0, image.width, image.height, // source size
                         0, 0, canvas.width, newHeight);  // destination size
    

    Canvas 会帮你剪裁。

    如果你想让目标垂直位置居中,你可以这样做:

    var destY = (canvas.height - image.height) / 2;
    
    ctx.drawImage(image, 0, 0, image.width, image.height,    // source size
                         0, destY, canvas.width, newHeight); // destination size
    

    【讨论】:

    • 你的答案我就快到了。好奇,如果我希望 sourceY 不是 0,我本来希望能够 ctx.drawImage(image, 0, 150, image.width, image.height, // source size 0, 0, canvas.width, newHeight); 当我有一个非零时,我得到一个空白画布。我会坚持下去,但任何帮助将不胜感激!
    • 我想通了。我不得不调整我的destY。感谢您的帮助!
    猜你喜欢
    • 2012-05-18
    • 2014-12-05
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 2015-01-09
    • 2011-04-30
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多