Javascript examples for Canvas:Mouse
HTML5 Canvas drawing ellipse with mouse
<html> <head> <title>Draw ellipse on canvas with mouse</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> <style id="compiled-css" type="text/css"> canvas {//from w w w. j a va 2 s . c o m cursor: crosshair; border: 1px solid #000000; } </style> <script type="text/javascript"> $(window).load(function(){ //Canvas var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var canvasx = $(canvas).offset().left; var canvasy = $(canvas).offset().top; var last_mousex = last_mousey = 0; var mousex = mousey = 0; var mousedown = false; //Mousedown $(canvas).on('mousedown', function(e) { last_mousex = parseInt(e.clientX-canvasx); last_mousey = parseInt(e.clientY-canvasy); mousedown = true; }); //Mouseup $(canvas).on('mouseup', function(e) { mousedown = false; }); //Mousemove $(canvas).on('mousemove', function(e) { mousex = parseInt(e.clientX-canvasx); mousey = parseInt(e.clientY-canvasy); if(mousedown) { ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas //Save ctx.save(); ctx.beginPath(); var scalex = 1*((mousex-last_mousex)/2); var scaley = 1*((mousey-last_mousey)/2); ctx.scale(scalex,scaley); var centerx = (last_mousex/scalex)+1; var centery = (last_mousey/scaley)+1; ctx.arc(centerx, centery, 1, 0, 2*Math.PI); ctx.restore(); ctx.strokeStyle = 'black'; ctx.lineWidth = 5; ctx.stroke(); } //Output $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown); }); }); </script> </head> <body> <canvas id="canvas" width="800" height="500"></canvas> <div id="output"></div> </body> </html>