我正在构建一个网站,我需要用户能够选择图像(带有黑色标志的透明 gif)并选择颜色。我有所有带有透明背景的黑色 gif。
如何将 gif 的颜色(仅限黑色)更改为用户选择的颜色?我正在考虑为此使用 Canvas ,但我不确定......
最佳答案
您可以使用 Canvas 来实现此目的。没有必要像许多人建议的那样迭代像素缓冲区,我建议尽可能避免,原因有两个:
- 如果图像是从不同来源加载的,则可能会应用 CORS 限制
- 性能
有一种更简单的涉及复合模式的方法:
Live demo
/// load image here, then:
function render() {
/// this composite mode clears the canvas as well
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(img, 0, 0);
/// this mode fills in whatever, in the image
ctx.globalCompositeOperation = 'source-in';
/// color to change GIF to:
ctx.fillStyle = '#00c';
/// fill color into non-alpha pixels
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
复制模式在这里起作用,因为图像是我们想要绘制到 Canvas 上的唯一内容。如果您还需要绘制其他细节,请改用 source-over
并使用 clearRect()
手动清除 Canvas 。
提示:您还可以在顶部绘制另一个图像而不是填充颜色。
原始 GIF
更改为蓝色
ctx.fillStyle = '#00c';
更改为红色
ctx.fillStyle = '#c00';
等等
关于javascript - 使用 JavaScript 更改 GIF 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548074/