Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - html 5 canvas - get color of an image and then change the pixels with that color

I don't know if this is possible, I've never really used html canvas, but I am aware of

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

but how do I use this to get for example all the pixels with a certain color and change these pixels to white? So let's say I have a pixel colored red:

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

that's the simple version of what I would like but not sure how to do that...

anyone any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do something like this (here's the canvas cheat sheet):

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...