简体   繁体   中英

Issue on Drawing Straight Line with Mouse Down and Move Event

Can you please take a look at following demo and let me know how I can enable the code to draw 100% straight Line on the canvas?

 $(function() { var drawLine = false; var theCanvas = document.getElementById('map'); var ctx = theCanvas.getContext('2d'); theCanvas.width = 420; theCanvas.height = 300; var canvasOffset = $('#map').offset(); $('#map').mousemove(function(e) { if (drawLine === true) { ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); ctx.stroke(); } }); $('#map').mousedown(function() { drawLine = true; ctx.strokeStyle = 'blue'; ctx.lineWidth = 5; ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); }); $(window).mouseup(function() { drawLine = false; }); }); 
 #map{border:solid; margin-top: 50px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <canvas id="map"></canvas> 

As you can see the code is working fine but what I want is drawing a straight line on drawing

Thanks

You would need to have 2 canvases:

  1. temporary for animation
  2. permanent to store drawing.

Algorithm:

  1. ondown write start coordinates.
  2. onmove record endpoint, clear canvas 1, draw a line on canvas 1 from start point to end point.
  3. onup draw final line on 2nd canvas clear 1st canvas.

Too lazy create second canvas (it'll clear it every try now); Put a comment where pass different canvas for permanent draw

 $(function() { var drawLine = false; var theCanvas = document.getElementById('map'); var finalPos = {x:0, y:0}; var startPos = {x:0, y:0}; var ctx = theCanvas.getContext('2d'); theCanvas.width = 420; theCanvas.height = 300; var canvasOffset = $('#map').offset(); function line(cnvs) { cnvs.beginPath(); cnvs.moveTo(startPos.x, startPos.y); cnvs.lineTo(finalPos.x, finalPos.y); cnvs.stroke(); } function clearCanvas() { ctx.clearRect(0, 0, theCanvas.width, theCanvas.height); } $('#map').mousemove(function(e) { if (drawLine === true) { finalPos = {x: e.pageX - canvasOffset.left, y:e.pageY - canvasOffset.top}; clearCanvas(); line(ctx); } }); $('#map').mousedown(function(e) { drawLine = true; ctx.strokeStyle = 'blue'; ctx.lineWidth = 5; ctx.lineCap = 'round'; ctx.beginPath(); startPos = { x: e.pageX - canvasOffset.left, y: e.pageY - canvasOffset.top}; }); $(window).mouseup(function() { clearCanvas(); // Replace with var that is second canvas line(ctx); finalPos = {x:0, y:0}; startPos = {x:0, y:0}; drawLine = false; }); }); 
 #map{border:solid; margin-top: 50px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <canvas id="map"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM