Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. function draw(e) {
  2. // stop the function running when they are not mouse down
  3. // false -> return 不觸發 function
  4. if (!isDrawing) return;
  5. // 設置線條顏色用 hsl 方式,並隨著 hue 值改變
  6. ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
  7. // 路徑繪製時,須先呼叫 beginPath() 產生路徑
  8. ctx.beginPath();
  9. // 接著路徑指針移到起始位置
  10. ctx.moveTo(lastX, lastY);
  11. // 將目前滑鼠位置與起始位置連接起來
  12. ctx.lineTo(e.offsetX, e.offsetY)
  13. // 把線條繪製出來
  14. ctx.stroke();
  15. // update lastX & lastY
  16. // 將最後滑鼠停止的位置放入 X, Y 以作為下一次的起始位置
  17. [lastX, lastY] = [e.offsetX, e.offsetY];
  18. }
  19.  
  20.  
  21.  
  22. // 滑鼠按鍵按下將 isDrawing flag 打開!
  23. canvas.addEventListener("mousedown", (e) => {
  24. isDrawing = true;
  25. // 當使用者點下滑鼠,在移動之前,先更新初始位置 (若沒這步,會因為一開始宣告變數位置為 0 而使線條永遠都從左上開始)
  26. [lastX, lastY] = [e.offsetX, e.offsetY];
  27. });
  28. // 滑鼠只要一移動就觸發 function draw
  29. canvas.addEventListener("mousemove", draw);
  30. // 滑鼠按鍵放開後停止
  31. canvas.addEventListener("mouseup", () => isDrawing = false);
  32. // 滑鼠游標移出渲染環境則停止
  33. canvas.addEventListener("mouseout", () => isDrawing = false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement