2010-08-11 70 views
1

下面是在Firefox中完美运行的代码,但我不明白为什么它在Webkit浏览器中无法使用!注意:我使用jQuery来选择画布元素。HTML5 Canvas翻转垂直功能适用于Firefox,但不适用于Chrome或Safari。为什么?

(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]; 

    } 
)(); 

回答

3

编辑:我打了这一点,并得到它的工作。问题是当你设置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(); 
} 
+0

@Mathew实际上,其他使用getImageData()(如灰度或反转)的滤镜对本地图像工作得很好。它似乎只是这一个flipV滤波器有问题。 我以前曾尝试过负缩放,但遇到了“INDEX_SIZE_ERR”问题。刚刚意识到这是因为我使用drawImage也裁剪了源代码,并将错误的高度var放在了上面。 你说得对,负面缩放比修改imageData更容易,我仍然想知道为什么我的过滤器在FF而不是Webkit中工作。 – talentedmrjones 2010-08-11 16:39:57

+1

我有一种感觉,那个新阵列可能与它有关。感谢您的试验和确认! 你的确是正确的,否定缩放是一个更好,更容易,更优雅的处理翻盖的方式,所以我会继续使用该方法。 – talentedmrjones 2010-08-11 21:06:34

相关问题