tal*_*nes 1 html javascript canvas getimagedata
下面的代码在 Firefox 中运行得很好,但我不明白为什么它在 Webkit 浏览器中不起作用!注意:我使用 jQuery 来选择画布元素。
(function()
{
flipV=function(imageData)
{
var n = new Array();
var d = imageData.data;
// loop through over row of pixels
for (var row=0;row<imageData.height;row++)
{
// loop over every column
for (var col=0;col<imageData.width;col++)
{
var si,di,sp,dp;
// source pixel
sp=(imageData.width*row)+col;
// destination pixel
dp=(imageData.width*((imageData.height-1)-row))+col;
// source and destination indexes, will always reference the red pixel
si=sp*4;
di=dp*4;
n[di]=d[si]; // red
n[di+1]=d[si+1]; // green
n[di+2]=d[si+2]; // blue
n[di+3]=d[si+3]; // alpha
}
}
imageData.data=n;
return imageData;
};
var imgs = ['/images/myimage.png'];
var $c=$('#canvas');
var cxt=$c[0].getContext('2d');
var w=$c.width();
var h=$c.height();
var img1 = new Image();
img1.onload=function()
{
cxt.drawImage(img1,0,0,img1.width,img1.height,0,0,w,h);
imageData = flipV(cxt.getImageData(0,0,w,h));
cxt.putImageData(imageData,0,0)
};
img1.src=imgs[0];
}
)();
Run Code Online (Sandbox Code Playgroud)
编辑:我玩了一下,并让它发挥作用。问题是当你设置imageData.data = n. 看起来 Chrome/WebKit 无法使用不同的data数组。为了使其工作,我将上下文对象传递给flipV并调用createImageData(imageData.width, imageData.height)以获取新的 ImageData 对象、 setn = newImageData.data和 returned newImageData。
我将剩下的留在这里供参考:
不过,有一种更简单、最有可能更快的方法来翻转图像,它可以跨域工作。您可以使用该scale函数自动翻转沿 y 轴绘制的所有内容。你只需要确保打电话save()并restore()记住调整位置,因为一切都翻转了。
function drawVFlipped(ctx, img) {
ctx.save();
// Multiply the y value by -1 to flip vertically
ctx.scale(1, -1);
// Start at (0, -height), which is now the bottom-left corner
ctx.drawImage(img, 0, -img.height);
ctx.restore();
}
Run Code Online (Sandbox Code Playgroud)