通过跟随鼠标光标绘制画布线 [英] canvas draw line by following mouse cursor
问题描述
这是我通过按下/释放鼠标按钮在画布上绘制线条的方式.但这并不是我想要得到的:通过按鼠标按钮可以设置一条直线的起点,终点将跟随鼠标光标.但该线应始终是一条直线-不能像现在那样绘制一些曲线.松开鼠标键,即可完成/修复该行.
This is how I'm drawing a line in a canvas by pressing/releasing the mouse button. But it is not exactly what I try to get: By pressing the mouse button the starting point of a stright line is beeing set, the end point will follow the mouse cursor. But the line should be always a straight line - not drawing of some curves, like it is be done now. By releasing the mouse button the line is finished/fixed.
因此,使用者应能够在画布上的任何位置以任何方向/旋转方向绘制直线.按下鼠标按钮可以起点,然后释放直线终点.
With that the use should be able to draw straight line anywhere on the canvas with any orientation/rotation. Pressing mouse button for starting point and releasing for end point of a straight line.
$(function() {
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = 420;
theCanvas.height = 300;
var canvasOffset = $('#paint').offset();
$('#paint').mousemove(function(e) {
if (letsdraw === true) {
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$('#paint').mousedown(function() {
letsdraw = true;
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
});
$(window).mouseup(function() {
letsdraw = false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="paint"></canvas>
推荐答案
you need to erase what's on the canvas once it's painted if you want to modify it
( with ctx.clearRect() );
看看这个:
$(function() {
var letsdraw ;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = 420;
theCanvas.height = 300;
var canvasOffset = $('#paint').offset();
$('#paint').mousemove(function(e) {
if (letsdraw) {
ctx.clearRect(0,0,theCanvas.width,theCanvas.height);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(letsdraw.x, letsdraw.y);
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$('#paint').mousedown(function(e) {
letsdraw = {
x:e.pageX - canvasOffset.left,
y:e.pageY - canvasOffset.top
}
});
$(window).mouseup(function() {
letsdraw = null;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="paint"></canvas>
这篇关于通过跟随鼠标光标绘制画布线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!