代码之家  ›  专栏  ›  技术社区  ›  talentedmrjones

HTML5画布垂直翻转功能在Firefox中工作,但在Chrome或Safari中不工作。为什么?

  •  1
  • talentedmrjones  · 技术社区  · 16 年前

    下面是在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];
    
        }
    )();
    
    1 回复  |  直到 16 年前
        1
  •  4
  •   Matthew Crumley    16 年前

    编辑: imageData.data = n . 看起来Chrome/WebKit无法与其他浏览器一起工作 data 数组。为了让它工作,我将context对象传递给 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();
    }