我有一些代码,当我单击鼠标(mousedown事件和mousemove事件)时移动鼠标时会画一条线。
我还希望从该点的起点(我第一次单击该点,mousedown事件)到结束(我将鼠标事件,mouseup事件抬起)绘制一条直线。
(function() {
var canvas = document.querySelector('#paint');
var ctx = canvas.getcontext('2d');
var sketch = document.querySelector('#sketch');
var sketch_style = getcomputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var mouse = {
x: 0,y: 0
};
var last_mouse = {
x: 0,y: 0
};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove',function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
},false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown',function(e) {
canvas.addEventListener('mousemove',onPaint,false);
},false);
canvas.addEventListener('mouseup',function() {
canvas.removeEventListener('mousemove',false);
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x,last_mouse.y);
ctx.lineTo(mouse.x,mouse.y);
ctx.closePath();
ctx.stroke();
};
}());
#sketch{
width: 100%;
height: 200px;
background-color: #CCCCCC;
}
<div id="sketch">
<canvas id="paint">
</canvas>
</div>