javascript - html 5 canvas - 获取图像的颜色,然后使用该颜色更改像素

标签 javascript html image canvas

我不知道这是否可能,我从来没有真正使用过html canvas,但我知道

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

但是我如何使用它来获取例如所有具有特定颜色的像素并将这些像素更改为白色? 假设我有一个红色像素:

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

这是我想要的简单版本,但不确定如何去做......

有人有什么想法吗?

最佳答案

做这样的事情(这里是 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>

希望对您有所帮助。

关于javascript - html 5 canvas - 获取图像的颜色,然后使用该颜色更改像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12992681/

相关文章:

html - 如何像在媒体上一样创建全屏背景图像?

javascript - jquery命令统计jpg文件个数

javascript - 无法点击下拉子菜单链接

javascript - jQuery 动画和 scrollTop

Javascript : "extend" an object without an instance

html - IE 中两个相邻 div 之间的奇怪间隙

java - 如何将 "Player image"添加到 Java 中?

javascript - ExtJS : how to make a custom modal window with MessageBox buttons?

html - BMobilize 用于对网站进行移动优化?

javascript - 使用循环将内容添加到多个类,但每个类中只有 1 个元素接收内容