Javascript examples for Canvas:Mouse
add mouse event in drawn canvas component
<!doctype html> <html> <head> <!-- reset css --> <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> <style> canvas{border:1px solid red;} </style> <script> $(function(){//from ww w.ja va 2 s . com var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var $canvas=$("#canvas"); var canvasOffset=$canvas.offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; ctx.strokeStyle = "black"; ctx.fillStyle = "red"; ctx.globalAlpha = 1.0; ctx.lineWidth = 0.5; ctx.font="14px verdana"; var centerX=150; var centerY=150; var radius=120; var arg=1; var start=0; var end=Math.PI/8; var shapes=[]; for(var k=0;k<10;k++){ start+=Math.PI/8; end+=Math.PI/8; x1 = centerX-radius*Math.sin(-arg*start)*0.9; y1 = centerY-radius*Math.cos(-arg*start)*0.9; x2 = centerX-radius*Math.sin(-arg*start)*0.95; y2 = centerY-radius*Math.cos(-arg*start)*0.95; x3 = centerX-radius*Math.sin(-arg*end)*0.95; y3 = centerY-radius*Math.cos(-arg*end)*0.95; x4 = centerX-radius*Math.sin(-arg*end)*0.9; y4 = centerY-radius*Math.cos(-arg*end)*0.9; var s={x1:x1,y1:y1,x2:x2,y2:y2,x3:x3,y3:y3,x4:x4,y4:y4,k:k}; shapes.push(s); Shape(s,k,true); } $results=$("#results"); $("#canvas").mousemove(function(e){handleMouseMove(e);}); function handleMouseMove(e){ e.preventDefault(); e.stopPropagation(); mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); for(var k=0;k<shapes.length;k++){ Shape(shapes[k],k,false); if(ctx.isPointInPath(mouseX,mouseY)){ $results.text("Last mouseover: "+k); } } } function Shape(s, k, draw){ ctx.fillStyle="red"; ctx.beginPath(); ctx.moveTo(s.x1,s.y1); ctx.lineTo(s.x2,s.y2); ctx.lineTo(s.x3,s.y3); ctx.lineTo(s.x4,s.y4); ctx.lineTo(s.x1,s.y1); if(draw){ ctx.fill(); ctx.stroke(); ctx.fillStyle="blue"; ctx.fillText(k,(s.x2+s.x3)/2,(s.y2+s.y3)/2); } } }); // end $(function(){}); </script> </head> <body> <p id="results">Hover mouse over shapes.</p> <canvas id="canvas" width="300" height="300"></canvas> </body> </html>