0

Lets assume I generate many randomly positioned words in canvas. I want to be able to detect which text im hovering over. How is this done technically? I mean I am familiar with mouse circle collisions but not with text.

I assume I also have to use the pythagoras distance formula:

Here a more complete jsfiddle: https://jsfiddle.net/testopia/o7gL6ge9/1/

text = {
  x: 50,
  y: 100
}

function collision(m1, m2, textPos) {
  var x = m1 - text.x;
  var y = m2 - text.y;

  return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}


if (collision(event.clientX, event.clientY, text) < 10) {
    console.log('Hello World');
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Asperger
  • 3,064
  • 8
  • 52
  • 100
  • You want [picking](http://stackoverflow.com/questions/8578545/pixel-perfect-2d-mouse-picking-with-canvas). – ssube Jan 12 '16 at 20:52
  • Can you give an example of how the HTML element which will contain your randomly generated word will look like? – AGE Jan 12 '16 at 21:04
  • @AGE added the randomization. Have a look. – Asperger Jan 12 '16 at 21:12
  • @ssube had a look and the tutorial is pretty huge considering I am only trying to learn a non-perfect collision. – Asperger Jan 12 '16 at 21:16
  • The concept of picking is not terribly simple, since you have to handle rotation and scaling. If you have a scenegraph, it becomes easier, but is still complex. – ssube Jan 12 '16 at 21:21
  • @ssube so hovering over text in a "cloud of words" in canvas is too much work right?. Would you rather the use of div tags then? I mean 32 people saw this post and non answered except you which means this topic seems to be very advanced – Asperger Jan 12 '16 at 21:28
  • @Asperger no? Picking is totally possible and fairly obvious once you've written it once or twice, but you do have to do real picking, not some approximation. – ssube Jan 12 '16 at 21:30
  • @ssube I will learn it then. Thanks man : ) – Asperger Jan 12 '16 at 21:33
  • @Asperger read this: http://stackoverflow.com/questions/18935737/text-collision-detection/18935984#18935984 if this takes you to the correct answer, I will mark this question as a duplicate. At the very least I hope it helps you find your solution. – AGE Jan 12 '16 at 21:38
  • 1
    @AGE thank you very much! – Asperger Jan 12 '16 at 21:48

0 Answers0