Languages
[Edit]
EN

JavaScript - is point in path on canvas

0 points
Created by:
Violetd
655

In this article, we would like to show you how to check if point is in the path on canvas using JavaScript.

Quick solution:

var canvas = document.querySelector('#my-canvas');

var context = canvas.getContext('2d');

context.isPointInPath(10, 10); // isPointInPath(x, y)

 

Practical example

In this example, we present how to use isPointInPath() method to check if a point is within the current path (square).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    #my-canvas { border: 1px solid gray; }

  </style>
</head>
<body>
  <canvas id="my-canvas" width="200" height="200"></canvas>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');
    
    context.strokeStyle = '#28a745';
    context.rect(20, 20, 100, 100); // rect(x, y, width, height)
    context.stroke();

    // point A
    console.log(context.isPointInPath(50, 50)); // true
    
    // point B
    console.log(context.isPointInPath(90, 90)); // true
    
    // point C
    console.log(context.isPointInPath(150, 150)); // false

  </script>
</body>
</html>

Visualization of the points we check:

JavaScript - is point in path on canvas (visualization)
JavaScript - is point in path on canvas (visualization)

Note:

You can draw the points using drawPoint() method from this article.

 

See also

  1. JavaScript - how to draw point on canvas element?

References

  1. CanvasRenderingContext2D.isPointInPath() - Web APIs | MDN

Alternative titles

  1. JavaScript - is point in path on HTML canvas element
  2. JavaScript - isPointInPath() usage example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join