帮我写一段js代码实现洪水填充
以下是一个简单的JavaScript代码实现洪水填充效果:
function floodFill(canvas, x, y, fillColor) {
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixelStack = [[x, y]];
const targetColor = getPixel(imageData, x, y);
if (targetColor === fillColor) {
return;
}
while (pixelStack.length) {
const [x, y] = pixelStack.pop();
const color = getPixel(imageData, x, y);
if (color === targetColor) {
setPixel(imageData, x, y, fillColor);
if (x > 0) {
pixelStack.push([x - 1, y]);
}
if (x < canvas.width - 1) {
pixelStack.push([x + 1, y]);
}
if (y > 0) {
pixelStack.push([x, y - 1]);
}
if (y < canvas.height - 1) {
pixelStack.push([x, y + 1]);
}
}
}
ctx.putImageData(imageData, 0, 0);
function getPixel(imageData, x, y) {
const index = (y * imageData.width + x) * 4;
return (
imageData.data[index] +
',' +
imageData.data[index + 1] +
',' +
imageData.data[index + 2] +
',' +
imageData.data[index + 3]
);
}
function setPixel(imageData, x, y, color) {
const index = (y * imageData.width + x) * 4;
const [r, g, b, a] = color.split(',');
imageData.data[index] = r;
imageData.data[index + 1] = g;
imageData.data[index + 2] = b;
imageData.data[index + 3] = a;
}
}
这段代码实现了洪水填充效果,即将图像中相邻的、颜色相同的像素点全部填充成指定的颜色。它的参数包括要填充的画布、填充起点的坐标、以及要填充的颜色。它使用了getImageData和putImageData方法来获取和设置像素点的颜色,使用了一个栈来保存需要填充的像素点坐标。同时,为了方便处理颜色,我们将一个像素的颜色表示为四个分量的字符串形式,即"r,g,b,a"。
原文地址: https://www.cveoy.top/t/topic/L9Y 著作权归作者所有。请勿转载和采集!