html5 canvas: clipping by color

感情迁移 提交于 2019-12-06 09:53:42

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/7348618/html5-canvas-clipping-by-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!