Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript canvas context.drawImage在不同浏览器中的差异?_Javascript_Html_Canvas_Drawimage - Fatal编程技术网

Javascript canvas context.drawImage在不同浏览器中的差异?

Javascript canvas context.drawImage在不同浏览器中的差异?,javascript,html,canvas,drawimage,Javascript,Html,Canvas,Drawimage,在尝试跨浏览器使用HTML5画布API缩放和裁剪图像时,我遇到了一个非常奇怪的问题 具体地说,我正在努力找到图像的中心,并使用上下文API中的这些参数根据其宽度和高度裁剪正方形 context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); 下面是我正在使用的代码示例: <!DOCTYPE html> <html> <body> <p>Image to use:</p> &

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

具体地说,我正在努力找到图像的中心,并使用上下文API中的这些参数根据其宽度和高度裁剪正方形

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>

要使用的图像:

画布:

您的浏览器不支持HTML5画布标记。 window.onload=函数(){ var c=document.getElementById(“myCanvas”); var ctx=c.getContext(“2d”); var img=document.getElementById(“尖叫”); ctx.drawImage(img,0,25,220,277,0,0,150,188); }
您可以在此处尝试演示:

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

我会上传图片,但stackoverflow有一个任意的规则,在我有更高的声誉之前不允许我发布图片


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

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

这里是两张图片的链接:Safari:Chrome:再次,我不能将它们添加到帖子中,因为我没有足够的声誉。啊,就是这样!我只需要通过创建$ctx.drawImage(img,0,25,220,252,0,0,150,188)的偏移量来降低高度;这起作用了。谢谢大家!@Nityoberoi没问题!:)