|
| 1 | +# JS30-Day8-Fun with HTML5 Canvas |
| 2 | +使用 Canvas 讓我們可以在網頁上畫畫的一個小實作 |
| 3 | + |
| 4 | +## 以下內容是實作中的步驟: |
| 5 | +### 1. 建立 Canvas 畫布 |
| 6 | +```javascript |
| 7 | +// 利用 draw 建立畫布,且畫布的內容是 2d 的 |
| 8 | +const canvas = document.querySelector('#draw'), |
| 9 | + ctx = canvas.getContext('2d'); |
| 10 | + |
| 11 | +// 設定畫布大小 |
| 12 | +canvas.width = window.innerWidth; |
| 13 | +canvas.height = window.innerHeight; |
| 14 | +``` |
| 15 | + |
| 16 | +#### 補充: |
| 17 | +因為在這邊看到 innerWidth,innerHeight,所以在此補充一下 innerWidth vs. outerWidth vs. width 的差別: |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +可以了解到: |
| 22 | +* innerWidth: 不包括 border,包括 padding |
| 23 | +* outerWidth: 包括 border 和 padding |
| 24 | +* width: 只包括該 DOM Element |
| 25 | +然後 height 也是一樣的規則喔~~ |
| 26 | + |
| 27 | +#### 2. 寫一些繪圖的設定 |
| 28 | +```javascript |
| 29 | +ctx.strokeStyle = '#BADA55'; // 設定勾勒圖形時用的顏色 |
| 30 | +ctx.lineJoin = 'round'; // 讓線條轉彎時它的拐角是圓的 |
| 31 | +ctx.lineCap = 'round'; // 讓線條末端是圓的 |
| 32 | +ctx.lineWidth = 100; // 線條寬度 |
| 33 | + |
| 34 | +let isDrawing = false, // 判斷是否繼續繪畫 |
| 35 | + lastX = 0, // 設定從哪裡開始繪畫/哪裡結束繪畫的初始值 |
| 36 | + lastY = 0; |
| 37 | +``` |
| 38 | + |
| 39 | +### 3. 建立繪畫的函式並建立監聽事件 |
| 40 | +```javascript |
| 41 | +function draw(e) { |
| 42 | + if(!isDrawing) { |
| 43 | + return; |
| 44 | + } else { |
| 45 | + // 開始畫線 |
| 46 | + ctx.beginPath(); |
| 47 | + ctx.moveTo(lastX, lastY); |
| 48 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 49 | + ctx.stroke(); |
| 50 | + // 利用解構重新指定 lastX 和 lastY 值 |
| 51 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +canvas.addEventListener('mousemove', draw); |
| 56 | +canvas.addEventListener('mousedown', (e) => { |
| 57 | + // 從滑鼠按下的點開始畫 |
| 58 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 59 | + isDrawing = true; |
| 60 | +}); |
| 61 | +canvas.addEventListener('mouseup', () => isDrawing = false); |
| 62 | +``` |
| 63 | +此時就能在網頁上繪畫了,下一步是新增一些變化 |
| 64 | + |
| 65 | +### 4. 新增繪畫時線條的變化(顏色,線寬) |
| 66 | +這邊和原程式碼有些不同,有按照自己的想法修改 |
| 67 | +```javascript |
| 68 | +let hue = 0; |
| 69 | +let direction = true; |
| 70 | + |
| 71 | +function draw(e) { |
| 72 | + if(!isDrawing) { |
| 73 | + return; |
| 74 | + } else { |
| 75 | + ctx.beginPath(); |
| 76 | + ctx.moveTo(lastX, lastY); |
| 77 | + ctx.lineTo(e.offsetX, e.offsetY); |
| 78 | + ctx.stroke(); |
| 79 | + [lastX, lastY] = [e.offsetX, e.offsetY]; |
| 80 | + |
| 81 | + // 控制顏色 |
| 82 | + ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; |
| 83 | + hue+= 10; |
| 84 | + |
| 85 | + // 控制線寬 |
| 86 | + if(ctx.lineWidth >= 20 || ctx.lineWidth < 5) { |
| 87 | + direction = !direction; |
| 88 | + } |
| 89 | + direction === true ? ctx.lineWidth++ : ctx.lineWidth--; |
| 90 | + } |
| 91 | +} |
| 92 | +``` |
0 commit comments