Fred J. Fred J. - 1 year ago 61
Javascript Question

check if canvas pixel is of a given color

A canvas has CSS

background-color: #D3D3D3;
and one property
ctx.fillStyle = "#000";

This JS code needs to leave the stroke intact and make every thing else transparent background. How can this be achieved?

imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;

let clearBack = imageData;
for (var i = 3; i < clearBack.length; i += 4) {
if (pixle is not black) { //if pixel belongs to the stroke leave it
clearBack[i] = 0;

Answer Source

You are close. You can go through every 4 pixels (red green blue alpha) and check each color with the imageData. Then if its not black, do what you want with it.

You can use putImageData to rewrite any modified pixels back to the screen. Make sure you keep the original ImageData object in your imageData var though.

imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); //take away the .data

var r, g, b, a;

for(var i = 0; i+3 <; i+=4) {
    r =[i];
    g =[i+1];
    b =[i+2];
    a =[i+3];

    if((r > 0 || g > 0 || b > 0) && a > 0) { // if pixel is not black, and not transparent         [i+3] = 0; //set alpha to 0

ctx.putImageData(imageData, 0, 0); //put the imageData back to the screen

Heres a fiddle. I was doing something slightly different there but you get the idea.