【问题标题】:Canvas - flip half the image画布 - 将图像翻转一半
【发布时间】:2012-12-18 12:18:49
【问题描述】:

我在画布中有一些图像数据,现在我需要将图像的左半部分翻转并应用到右侧,就像镜像效果一样。

示例,由此而来:

到这里:

我已经做到了(我已经准备好了图像数据):

ctx.drawImage(this, 0, 0, 960, 540);
var imgData = ctx.getImageData(0,0,960,540);
// loop through the data and apply mirror ??

宽度和高度是已知的。有什么想法吗?

【问题讨论】:

    标签: javascript canvas html5-canvas image-manipulation


    【解决方案1】:
    1. 循环遍历图像数据
    2. 如果当前像素在图像的左半边,则将其复制到右侧的位置:
    for(var y = 0; y < height; y++) {
        for(var x = 0; x < width / 2; x++) { // divide by 2 to only loop through the left half of the image.
            var offset = ((width* y) + x) * 4; // Pixel origin
    
            // Get pixel
            var r = data[offset];
            var g = data[offset + 1];
            var b = data[offset + 2];
            var a = data[offset + 3];
    
            // Calculate how far to the right the mirrored pixel is
            var mirrorOffset = (width - (x * 2)) * 4;
    
            // Get set mirrored pixel's colours 
            data[offset + mirrorOffset] = r;
            data[offset + 1 + mirrorOffset] = g;
            data[offset + 2 + mirrorOffset] = b;
            data[offset + 3 + mirrorOffset] = a;
        }
    }
    

    我没有对此进行测试,但它应该(或多或少)有效,或者至少让您知道如何去做。

    【讨论】:

    • 看起来不错,但这里有问题。生成的图像看起来很扭曲,好像偏移量没有正确计算。
    • @David:你能发个截图吗?
    • 这很尴尬,该网站从这里被屏蔽了,@David -.- 你能试试imgur.com 吗? :P
    • @David:啊,我真傻!我忘记了每个像素在数据数组中占用 4 个“槽”,所以偏移量必须是pixels * 4。编辑了答案。我看到一些颜色变化,这可能是由于偏移量有点偏。 (您可能需要添加一个小的 int)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多