7

我不知道这是否可能,我从未真正使用过 html 画布,但我知道

var imgPixels = canvasContext.getImageData(0, 0, canvas.width, canvas.height);

但是我如何使用它来获取具有某种颜色的所有像素并将这些像素更改为白色?所以假设我有一个红色的像素:

if(pixel==red){
    pixel = white;
}

这是我想要的简单版本,但不知道该怎么做......

有人有什么想法吗?

4

2 回答 2

7

做这样的事情(这里是画布备忘单):

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

const { width, height } = canvas;

const gradient = context.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0.25, "#FF0000");
gradient.addColorStop(0.75, "#000000");

context.fillStyle = gradient;

context.fillRect(0, 0, width, height);

setTimeout(() => {
    const image = context.getImageData(0, 0, width, height);
    const { data } = image;
    const { length } = data;

    for (let i = 0; i < length; i += 4) { // red, green, blue, and alpha
        const r = data[i + 0];
        const g = data[i + 1];
        const b = data[i + 2];
        const a = data[i + 3];

        if (r === 255 && g === 0 && b === 0 && a === 255) { // pixel is red
            data[i + 1] = 255; // green is set to 100%
            data[i + 2] = 255; // blue is set to 100%
            // resulting color is white
        }
    }

    context.putImageData(image, 0, 0);
}, 5000);
<p>Wait for 5 seconds....</p>
<canvas width="120" height="120"></canvas>

希望有帮助。

于 2012-10-20T21:21:30.943 回答
4

当你得到 时getImageData(),你有一个带有datawidth的对象height

您可以循环data,其中包含像素数据。它以 4 个为一组,分别为红色、绿色、蓝色和 alpha。

因此,您的代码可以查找红色像素(您必须决定是什么构成了红色像素)并将红色、绿色和蓝色全部设置为打开(将其更改为白色)。然后,您可以使用更新的像素数据putImageData()替换。canvas

// You will need to do this with an image that doesn't violate Same Origin Policy.
var imgSrc = "image.png";
var image = new Image;

image.addEventListener("load", function() {

    var canvas = document.getElementsByTagName("canvas")[0];
    var ctx = canvas.getContext("2d");

    canvas.width = image.width;
    canvas.height = image.height;

    ctx.drawImage(image, 0, 0);

    var imageData = ctx.getImageData(0, 0, image.width, image.height);
    var pixels = imageData.data;
    var i;

    for (i = 0; i < pixels.length; i += 4) {
        // Is this pixel *red* ?
        if (pixels[i] > 100) {
            pixels[i] = 255;
            pixels[i + 1] = 255;
            pixels[i + 2] = 255;
        }
    }

    ctx.putImageData(pixels);

});

image.src = imgSrc;​
于 2012-10-20T21:15:22.607 回答