Dronich Dronich - 5 months ago 44
Javascript Question

Is there a native way to address a non-rectangle object on canvas in js?

I've created a grid of several distorted rectangles made with Bezier curves. Each rectangle has its own color on the picture.

Let's say, I want to add hover effect for each of these rectangles, therefore I need to know its dimensions. Since I can fill or stroke the figure I assume that there is some way to get them, but I'm not sure.

Here is the example of the rectangles:

enter image description here

So the question is, is there some method in the canvas API with which I can achieve the desired effect?

Answer Source

Yes you can use isPointInPath(Path2D, x, y) method.

Note that if you don't use the Path2D object, you can also call it just with isPointInPath(x, y), but then it will check on the currently being drawn path (declared with beginPath()).

var ctx = canvas.getContext('2d');
var myPath = new Path2D();
myPath.bezierCurveTo(50, 100, 180, 10, 20, 10);
myPath.lineTo(50, 100);

function draw(hover) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = hover ? 'red' : 'green';

canvas.onmousemove = function(e) {
  var x = e.clientX - canvas.offsetLeft,
    y = e.clientY - canvas.offsetTop;
  var hover = ctx.isPointInPath(myPath, x, y)
<canvas id="canvas"></canvas>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download