canvas context.drawImage 浏览器之间的差异?

canvas context.drawImage differences across browsers?

我在尝试跨浏览器使用 HTML5 canvas API 缩放和裁剪图像时遇到了一个非常奇怪的问题。

具体来说,我正在尝试找到图像的中心并根据上下文 API[=16] 使用这些参数作为 specified 根据其宽度和高度裁剪正方形=]

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

这是我使用的代码示例:

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" width="220" height="277" src="img_the_scream.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="150" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 0, 25, 220, 277, 0, 0, 150, 188);
}
</script>

</body>
</html>

您可以在此处试用演示: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_canvas_drawimage2

该代码不会在 Safari 中的 canvas 中显示任何内容,但它可以正确缩放和裁剪 Chrome 中的图像。

我会上传图片,但 Whosebug 有一个任意规则,不允许我 post 图片,直到我有更高的声誉!

如有任何想法,我们将不胜感激!

Safari 中的问题可能是对源大小敏感,即您指定为源的区域与可用位图的对比。

例如,示例中的来源说:

//        source:  x, y , w  , h
ctx.drawImage(img, 0, 25, 220, 277, ...

这意味着位图的高度必须为 25+277 像素,当然情况并非如此,因为输入图像的高度仅为 277 像素。

尝试将源区域调整到图像内部,在这种情况下使用 y 偏移量降低高度:

ctx.drawImage(img, 0, 25, 220, 277-25,   0, 0, 150, 188);

要裁剪,请始终确保源区域在图像内部,f.ex。如果您想从所有方向裁剪 10 个像素:

var iw = img.naturalWidth;
var ih = img.naturalHeight;
var crop = 10;

ctx.drawImage(img, crop, crop, iw - crop*2, ih - crop*2, 0, 0, 150, 188);