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

前端 未结 2 845
时光说笑
时光说笑 2020-12-16 05:10

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, can         


        
2条回答
  •  误落风尘
    2020-12-16 05:50

    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);

    Wait for 5 seconds....

    Hope that helps.

提交回复
热议问题