[英]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? 您能否看一下下面的演示,并让我知道如何使代码在画布上绘制100%的直线?
$(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: 您将需要2张画布:
Algorithm: 算法:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.