Detect mouse collision canvas text (JS)

  canvas, collision, javascript, mouse, text

How can I detect whether my mouse is over a piece of text rendered on a Canvas? For example:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = '30px Arial'
ctx.fillText('Test', 100, 50)

If it is not possible to detect whether the mouse is over the actual text, I have thought about using .measureText to find the bounding box of the rendered text, and using that instead. But that doesn’t work very well for rotated text, and I am not sure how to find a rotated bounding box.

To summarise:

  1. Is it possible to detect mouseover events on text rendered on a canvas?
  2. If not, is there some way to use .measureText to find some kind of rotated bounding box?

Thank you in advance!

Source: Ask Javascript Questions

LEAVE A COMMENT