![](/img/trans.png)
[英]OffsetX in html5 canvas works with IE, Safari, Chrome but not with Firefox
[英]HTML5 Canvas flip vertical function works in Firefox but not Chrome or Safari. why?
這是在Firefox中運行良好的代碼,但我不明白為什么它在Webkit瀏覽器中不起作用! 注意:我使用jQuery來選擇canvas元素。
(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];
}
)();
編輯:我玩了一點,並讓它工作。 問題是當你設置imageData.data = n
。 看起來Chrome / WebKit無法使用不同的data
陣列。 為了使它工作,我將上下文對象傳遞給flipV
並調用createImageData(imageData.width, imageData.height)
來獲取一個新的ImageData對象,設置n = newImageData.data
,並返回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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.