繁体   English   中英

HTML5 Canvas翻转垂直功能适用于Firefox,但不适用于Chrome或Safari。 为什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM