html 5 canvas - 获取图像的颜色,然后用该颜色更改像素

时间:2012-10-20 21:06:46

标签: javascript html image canvas

我不知道这是否可行,我从未真正使用过html canvas,但我知道

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

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

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

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

任何想法?

2 个答案:

答案 0 :(得分:6)

做这样的事情(这里是canvas cheat sheet):

var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var pixelArray = imageData.data;
var length = pixelArray.length / 4; // 4 components - red, green, blue and alpha

for (var i = 0; i < length; i++) {
    var index = 4 * i;

    var r = pixelArray[index];
    var g = pixelArray[++index];
    var b = pixelArray[++index];
    var a = pixelArray[++index];

    if (r === 255 && g === 0 && b === 0 & a === 255) { // pixel is red
        pixelArray[--index] = 255; // blue is set to 100%
        pixelArray[--index] = 255; // green is set to 100%
        // resulting color is white
    }
}

context.putImageData(imageData, 0, 0);

这是一个现场演示:http://jsfiddle.net/36M6W/

答案 1 :(得分:4)

获得getImageData()后,您的对象包含datawidthheight

您可以遍历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;​