<canvas id="canvas" width="600" height="400" style="border: 1px solid black;"> </canvas>
<script type="text/javascript">
let canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
canvasLeft = canvas.getBoundingClientRect().left, //getBoundingClientRect()获取元素位置
canvasTop = canvas.getBoundingClientRect().top;
let imageData; //记录图像数据
let start = new Map([['x',null],['y',null]]);
let drag = false;//记录是否处于拖动状态
canvas.onmousedown = function (e) {
let pos = positionInCanvas(e, canvasLeft, canvasTop);
start.set('x', pos.x);
start.set('y', pos.y);
drag = true;
//记录imageData
imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
}
canvas.onmousemove = function (e) {
if(drag === true){
let pos = positionInCanvas(e, canvasLeft, canvasTop);
//相当于把扫描出来的线都擦掉,重新画
ctx.putImageData(imageData, 0, 0);
ctx.beginPath();
ctx.moveTo(start.get('x'), start.get('y'));
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
}
canvas.onmouseup = function (e) {
drag = false;
}
function positionInCanvas (e, canvasLeft, canvasTop) {//获取canvas中鼠标点击位置
return {
x:e.clientX - canvasLeft,
y:e.clientY - canvasTop
}
}
</script>