效果图:
HTML:
<canvas id="canvas" width="500" height="500" style="border: 1px solid;"></canvas>
CSS:
// 记录鼠标状态
let painting = false;
// 存储数鼠标按下的位置
let startPoint = {x:undefined,y:undefined};
// 获取canvas上下文
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
//通过onmousedown获取鼠标按下的 x , y 位置
canvas.onmousedown = function(v){
let x = v.offsetX;
let y = v.offsetY;
startPoint={x:x,y:y}
console.log(startPoint);
painting = true
}
//通过onmousemove获取鼠标移动的 x , y 位置
canvas.onmousemove=function(v){
let x = v.offsetX;
let y = v.offsetY;
let newPoint= { x : x , y : y }
console.log(newPoint);
if(painting){
drawLine(startPoint.x,startPoint.y,newPoint.x,newPoint.y)
startPoint = newPoint
}
}
//结束画笔
canvas.onmouseup=function(){
painting=false;
}
function drawLine(xStart,yStart,xEnd,yEnd){
//创建画笔
ctx.beginPath();
//设置线宽
ctx.lineWidth=3;
//画笔起点
ctx.moveTo(xStart,yStart)
ctx.lineTo(xEnd,yEnd)
//描边
ctx.stroke()
//展示路径
ctx.closePath()
}