Javascript examples for Canvas:Mouse
Mouse draw
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.js"></script> <style id="compiled-css" type="text/css"> canvas{border:1px solid red;} </style> <script type="text/javascript"> $(window).load(function(){/*from w w w . j a va 2s.c o m*/ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var lastX; var lastY; var strokeColor="red"; var strokeWidth=2; var canMouseX; var canMouseY; var canvasOffset=$("#canvas").offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; var isMouseDown=false; var imageObj=new Image(); imageObj.onload=function(){ ctx.save(); ctx.globalAlpha=.3; ctx.drawImage(this,0,0,canvas.width,canvas.height); ctx.restore(); } imageObj.src="https://www.java2s.com/style/demo/Google-Chrome.png"; function handleMouseDown(e){ canMouseX=parseInt(e.clientX-offsetX); canMouseY=parseInt(e.clientY-offsetY); $("#downlog").html("Down: "+ canMouseX + " / " + canMouseY); lastX=canMouseX; lastY=canMouseY; isMouseDown=true; } function handleMouseUp(e){ canMouseX=parseInt(e.clientX-offsetX); canMouseY=parseInt(e.clientY-offsetY); $("#uplog").html("Up: "+ canMouseX + " / " + canMouseY); // Put your mouseup stuff here isMouseDown=false; } function handleMouseOut(e){ canMouseX=parseInt(e.clientX-offsetX); canMouseY=parseInt(e.clientY-offsetY); $("#outlog").html("Out: "+ canMouseX + " / " + canMouseY); // Put your mouseOut stuff here isMouseDown=false; } function handleMouseMove(e){ canMouseX=parseInt(e.clientX-offsetX); canMouseY=parseInt(e.clientY-offsetY); $("#movelog").html("Move: "+ canMouseX + " / " + canMouseY); // Put your mousemove stuff here if(isMouseDown){ ctx.beginPath(); ctx.lineWidth=5; ctx.strokeStyle="#FF0000"; ctx.moveTo(lastX,lastY); ctx.lineTo(canMouseX,canMouseY); ctx.stroke(); lastX=canMouseX; lastY=canMouseY; } } $("#canvas").mousedown(function(e){handleMouseDown(e);}); $("#canvas").mousemove(function(e){handleMouseMove(e);}); $("#canvas").mouseup(function(e){handleMouseUp(e);}); $("#canvas").mouseout(function(e){handleMouseOut(e);}); }); </script> </head> <body> <br> Drag to draw on the map image <br> <canvas id="canvas" width="576" height="307"></canvas> </body> </html>