Skip to main content

[JS30] Day08: Fun with HTML5 Canvas

這堂課是教我們使用 Canvas 元素,滑鼠就是我們的畫筆,揮灑我們的創意吧!

HTML

首先一定要有個 Canvas 元素

<canvas id="draw" width="800" height="800"></canvas>

JavaScript

設定 Canvas 的內容(ctx),寬高為整個螢幕

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 基礎屬性,lineJoin與lineCap使得線與線的連結滑順、邊角圓潤
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.lineWidth = 10;
// ctx.globalCompositeOperation = "source-over"; 重疊屬性

innerHeight: https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight

innerWidth: https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth

draw() 繪畫函式,isDrawing控制繪畫與否,strokeStyle透過 hsl 給色,ctx.stroke繪製邊線,direction 控制lineWidth的正向或是反向增加。

let isDrawing = false;
let lastX = 0; //上一次繪畫的X
let lastY = 0; //上一次繪畫的Y
let hue = 0; // 色相
let direction = true;

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

ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.pageX, e.pageY);
ctx.stroke();
[lastX, lastY] = [e.pageX, e.pageY];
hue++;
if (ctx.lineWidth >= 500 || ctx.lineWidth <= 5) {
direction = !direction;
}
if (direction) {
ctx.lineWidth++;
} else {
ctx.lineWidth--;
}
}

Canvas overview: https://www.freecodecamp.org/news/full-overview-of-the-html-canvas-6354216fba8d/

hsl playground: https://mothereffinghsl.com/

在滑鼠點擊(mousedown)時,isDrawing 為 true,會繪製一個點(moveTo 跟 lineTo 相同位置),並設置了 lastX、lastY

canvas.addEventListener("mousedown", (e) => {
isDrawing = true;
[lastX, lastY] = [e.pageX, e.pageY];
ctx.moveTo(lastX, lastY);
ctx.lineTo(lastX, lastY);
ctx.stroke();
});

接著在滑鼠移動、滑鼠放開、滑鼠移出畫面各有不同的呼叫函式,滑鼠移出畫面防止在我們移出視窗又回來時,會有違和的繪畫效果。

canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", () => {
isDrawing = false;
});
canvas.addEventListener("mouseout", () => {
isDrawing = false;
});