前言
本文為「JavaScript 30」教學影片的學習筆記。
目標
練習操作 Canvas 畫布。
筆記
先取得 #draw 元素。
1 2
   | const canvas = document.querySelector('#draw'); const ctx = canvas.getContext('2d');
  | 
 
getContext() 方法返回一個用於在畫布上繪圖的環境。當前唯一合法値是 2d,代表二維繪圖。 
將畫布環境設定成目前瀏覽器的寬度與長度。
1 2
   | canvas.width = window.innerWidth; canvas.weight = window.innerHeight;
   | 
 
設定預設樣式。
1 2 3 4
   | ctx.strokeStyle = '#BADA55'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.lineWidth = 100;
   | 
 
strokeStyle 屬性代表筆觸顏色。 
lineJoin 屬性代表線條連接樣式。 
lineCap 屬性代表線條結束樣式。 
設定預設參數。
1 2 3 4 5
   | let isDrawing = false;  let lastX = 0;  let lastY = 0;  let hue = 0;  let direction = true; 
   | 
 
設定一個 draw() 函式,以操作 Canvas 畫布。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   | function draw(e) {     if (!isDrawing) return;      ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;      ctx.beginPath();      ctx.moveTo(lastX, lastY);     ctx.lineTo(e.offsetX, e.offsetY);     ctx.stroke();      [lastX, lastY] = [e.offsetX, e.offsetY];      hue++; 
           if (hue >= 360) {         hue = 0;     }
           if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {         direction = !direction;     }
           if (direction) {         ctx.lineWidth++;     } else {         ctx.lineWidth--;     } }
  | 
 
綁定 mousedown 和 mousemove 事件以開始畫圖。
1 2 3 4 5 6
   | canvas.addEventListener('mousedown', (e) => {     isDrawing = true;     [lastX, lastY] = [e.offsetX, e.offsetY]; });
  canvas.addEventListener('mousemove', draw);
  | 
 
綁定 mouseup 和 mouseout 事件以結束畫圖。
1 2 3
   | canvas.addEventListener('mouseup', () => isDrawing = false);
  canvas.addEventListener('mouseout', () => isDrawing = false);
  |