Graphic selection -isPointInPath (x, y)

Posted May 26, 20202 min read

isPointInPath(x, y) is a built-in method in canvas 2d, it can judge whether a point is in the path.
isPointInPath(x, y) The object is a path, so it is not good for text, fillRect(), strokeRect().
First, let s review the basic concepts of path:
When we use the getContext('2d') method of canvas to get the canvas context object ctx, an empty path collection is mounted on ctx.
After ctx.beginPath(), all the paths drawn will be added to this path collection. The isPointInPath(x, y) method determines whether the x and y points are in all paths in this path collection. This path need not be drawn, as long as there is a path in the path collection.
Note that the next time ctx.beginPath(), the path collection will be empty.

Next we look at the usage of isPointInPath.
I drew a polyline with three points and did not close it:


const ctx = canvas.getContext('2d');
console.log(ctx.isPointInPath(250,100)); //true

ctx.isPointInPath(250,100) returns true, that is, the point(250,100) is in the three enclosed paths.
To summarize briefly:

  1. A polyline composed of 3 points is drawn in the net path set, and it is not closed(it does not matter whether it is closed).
  2. The detection point(250,100) is in the figure surrounded by the three points above, and all ctx.isPointInPath(250,100) is true.
  3. The ctx.isPointInPath(250,100) method is executed before drawing, which means that the use of the isPointInPath(x, y) method does not need to actually draw the path.

At this time, you may think that if I use the mouse point as a detection point, every time the mouse moves, it must be judged whether it is in the graph. Is it necessary to draw the path every time the mouse moves?
The answer is yes, but we can encapsulate the steps of drawing a path into a method, which is convenient to be called in the mouse movement event. Such as:

function crtPath() {

When drawing:


When the mouse is selected:

canvas.addEventListener('mousemove', mousemoveFn);
function mousemoveFn(event) {
    const mousePos = getMousePos(event);
    const bool = ctx.isPointInPath(mousePos.x, mousePos.y);

/* Get the position of the mouse in the canvas * /
function getMousePos(event) {
const {clientX, clientY} = event;
const {top, left} = canvas.getBoundingClientRect();
const x = clientX-left;
const y = clientY-top;
return {x, y};

At this point, we can do some simple graphic selection projects, but in the face of larger projects, it is recommended that you use the idea of modules to modularize the above functions.
Please see the next chapter: Graphic Selection-Graphical Modularity

Source Address