Javascript examples for Canvas:Mouse
Getting the length of a line formed by dragging
<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"> #myCanvas{/* w w w .j a v a 2 s. co m*/ width: 100%; height: 100%; } </style> <script type="text/javascript"> $(window).load(function(){ var telemetry = { $canvas: $('#myCanvas'), startPosition: {x:0,y:0}, distance: 0, getMousePosition: function(event){ var position = { x: event.pageX - this.$canvas.offset().left, y: event.pageY - this.$canvas.offset().top } return position; }, getDistance: function(startPosition, endPosition){ var dx = endPosition.x - startPosition.x; var dy = endPosition.y - startPosition.y; return Math.sqrt((dx*dx) + (dy*dy)); }, onMouseDown: function(event){ this.startPosition = this.getMousePosition(event); }, onMouseUp: function(event){ this.distance = this.getDistance(this.startPosition, this.getMousePosition(event)); } } telemetry.$canvas.mousedown(function(event){ telemetry.onMouseDown(event); }).mouseup(function(event){ telemetry.onMouseUp(event); console.log('you dragged ' + telemetry.distance + 'px'); }); }); </script> </head> <body> <canvas id="myCanvas"></canvas> </body> </html>