【JavaScript】mouse event series

説明

  • mousedown:滑鼠按下去的瞬間→觸發事件
  • mouseout:滑鼠離開→觸發事件
  • mouseup:滑鼠按下、離開的瞬間→觸發事件

 

p Try to draw it ↓↓
canvas#canvas(width="300", height="300")
#canvas
 width: 300px
 height: 300px
 border: 1px solid #000
let isDrawing=false;
let lastX=0;
let lastY=0;
const ctx=canvas.getContext("2d");

function draw(e){
 if(!isDrawing){
  return;
 }

 ctx.beginPath();
 ctx.moveTo(lastX, lastY);
 ctx.lineTo(e.offsetX, e.offsetY);
 ctx.strokeStyle="#000000";
 
 [lastX, lastY]=[e.offsetX, e.offsetY];
 
 ctx.stroke();
}

//滑鼠按下→開始畫圖,計算起始座標
canvas.addEventListener("mousedown", (e) => {
 isDrawing = true;
 [lastX, lastY]=[e.offsetX, e.offsetY];
});

//滑鼠移動→繼續畫圖
canvas.addEventListener("mousemove", draw);
//滑鼠放掉→停止畫圖
canvas.addEventListener("mouseup", () => isDrawing = false);
//滑鼠離開→停止畫圖
canvas.addEventListener("mouseout", () => isDrawing = false);

Display
Try to draw it ↓↓