开发者

Detect mouseover and show tooltip text for dots on an HTML Canvas

开发者 https://www.devze.com 2023-02-03 19:30 出处:网络
Ive recently created a \"map\" although not very sophisticated (im working on it) it has the basic function and is generally heading in the right direction.

Ive recently created a "map" although not very sophisticated (im working on it) it has the basic function and is generally heading in the right direction.

If you look at it you can see a tiny red dots and on those tiny red dots i want to mouseover it and see text basically but ive had a bit of trouble getting the code right.

http://hummingbird2.x10.mx/website%20creation/mainpage.htm

This is all the code so far.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>Oynx Warrior</title>
 <link rel="stylesheet" type="text/css" href="mystyle.css" />

 </head>
 <body>
 <h1>Oynx Warrior</h1>

<canvas id="myCanvas" width="500" height="500" style="border:1px so开发者_如何学Pythonlid #c3c3c3;">
 Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">
 var c=document.getElementById("myCanvas");
 var cxt=c.getContext("2d");
 cxt.fillStyle="#red";
 cxt.beginPath();
 cxt.arc(50,50,1,0,Math.PI*2,true);
 cxt.closePath();
 cxt.fill();

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


Here are four options:

  1. Keep track of all the dots' locations and track the mousemove event on the body. When the mouse moves over a dot, re-draw the canvas with the text. When the mouse moves off, clear the canvas and re-draw it without the text. You have to write your own 'hit' detection code to compare the mouse position to the bounding boxes/radius of all dots. It's hard, but not impossible.

  2. Instead of one canvas for the entire map, use a canvas to create your custom dot, call toDataURL() on the canvas to get a string for it, create a new absolutely-positioned <div> element for each dot, and set the .style.backgroundImage = url('+myDotDataURL+');. Now you can just set the title attribute on each div, and let the browser handle the mouse detection and tooltip display for you. Downside: you will see the tooltip for a square area around the dot, not exactly the dot itself.

  3. Instead of HTML Canvas, go with SVG. In SVG drawn 'elements' are actual objects that have their own events and hit detection. With this you can draw custom dots and let the browser do all mouse hits for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消