问题
This image is loaded in an html5 canvas.
If a user presses at any point inside the square, I want to fill this area with a color. But just inside, the color stops at the black lines. You can think about the fill tool like in Windows Paint.
How can I solve this? Are there libraries for javascript for such a function to start with?
回答1:
What you are looking for is called a flood fill algorithm. Which basically will take the color of the pixel you clicked on as a seed. It will check for all the pixels that are connected to the seed pixel that have the same color of the seed and fill them to a desired color. There are two types of this algorithm: 8-directional and 4-directional. Where the neighbours are defined as such ( S = Seed, X = Connected ):
4-directional
----------------
| | X | |
----------------
| X | S | X |
----------------
| | X | |
----------------
8-directional
----------------
| X | X | X |
----------------
| X | S | X |
----------------
| X | X | X |
----------------
The recursive algorithm is like so (From Wikipedia):
Flood-fill (node, target-color, replacement-color):
1. If target-color is equal to replacement-color, return.
2. If the color of node is not equal to target-color, return.
3. Set the color of node to replacement-color.
4. Perform Flood-fill (one step to the west of node, target-color, replacement-color).
Perform Flood-fill (one step to the east of node, target-color, replacement-color).
Perform Flood-fill (one step to the north of node, target-color, replacement-color).
Perform Flood-fill (one step to the south of node, target-color, replacement-color).
5. Return.
回答2:
You might want to use the CanvasRenderingContext2D.isPointInPath()
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clicked = false;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.rotate(45);
ctx.beginPath();
ctx.rect(100, -100, 100, 100);
if (ctx.clicked) {
ctx.fillStyle = "blue";
ctx.fill()
}
ctx.stroke();
ctx.restore();
}
draw();
canvas.addEventListener('click', function(e) {
var bounds= canvas.getBoundingClientRect();
var mouseXY = [e.clientX-bounds.left, e.clientY-bounds.top]
ctx.clicked = ctx.isPointInPath(mouseXY[0], mouseXY[1]);
draw();
});
canvas {
border: 1px solid
}
<canvas id="canvas" height="500" width="500"></canvas>
来源:https://stackoverflow.com/questions/28955110/how-to-recognize-an-area-in-an-canvas-via-javascript