开发者

html5 canvas: clipping by color

开发者 https://www.devze.com 2023-04-03 07:49 出处:网络
is there any way to choose an area on the canvas by color and clip it? I want to be able to clip an undefined aread that the only thing in 开发者_运维百科common between all the pixels is that they all

is there any way to choose an area on the canvas by color and clip it? I want to be able to clip an undefined aread that the only thing in 开发者_运维百科common between all the pixels is that they all have the same color. thanks


Live Demo

Below is a way to select a color.. and do whatever you want with it. I pass a color I want to find iterate over every pixel and remove the color that matches, since Im not sure what you meant by clipping I assumed you mean remove. However please note on large images this method will be slow.

// Takes an array with 3 color components, rgb     
function removeColor(color){
    var canvasData = ctx.getImageData(0, 0, 256, 256),
        pix = canvasData.data;

    for (var i = 0, n = pix.length; i <n; i += 4) {
        if(pix[i] === color[0] && pix[i+1] === color[1] && pix[i+2] === color[2]){
             pix[i+3] = 0;   
        }
    }

    ctx.putImageData(canvasData, 0, 0);
}

removeColor([0,0,255]); // Removes blue.

And like Simon pointed out the code above will get the exact color. Below will grab the approximate color, which is good if you have colors overlapping or very close to each other.

Demo 2 with approximation

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号