Skip to main content

[JS30] Day08: Fun with HTML5 Canvas

使用 HTML5 畫布#

<!-- html -->
<canvas id="draw" width="800" height="800"></canvas>

畫布(canvas)設定#

選取畫布並設定為 2d#

實際上作畫的是在 canvas 的 context

const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');

畫布初始化#

畫布在初始化的時候要設定長寬,畫筆的顏色和形狀

function initializeCanvas() {
// 畫布長寬設定
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 畫筆顏色與形狀
ctx.strokeStyle = '#BADA55';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 10;
}
initializeCanvas();

window resize 時要重設畫布尺寸#

前面之所以把初始化畫布的內容寫成一個 function 是因為當使用者調整瀏覽器大小的時候,我們要跟著重設畫布的大小。

另外因為每次 resize canvas 時,原本ctx的設定會重置,所以要把畫筆相關的設定寫在 initializeCanvas()

window.addEventListener('resize', initializeCanvas);

繪圖函式#

let hue = 0;
function draw(e) {
if (!isDraw) {
return;
}
ctx.strokeStyle = `hsl(${hue}, 60%, 60%)`;
ctx.beginPath();
// start from
ctx.moveTo(lastX, lastY);
// go to
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
// Array destructuring
[lastX, lastY] = [e.clientX, e.clientY];
hue = (hue + 1) % 360;
}

其他關於 canvas 筆記 @ PJCHENder Evernote Canvas Rendering Context 2D @ MDN

事件監聽#

監聽使用者的滑鼠是不是處於點擊的狀態

let lastX = 0;
let lastY = 0;
let isDraw = false;
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mousedown', (e) => {
isDraw = true;
lastX = e.clientX;
lastY = e.clientY;
});
canvas.addEventListener('mouseup', () => (isDraw = false));
canvas.addEventListener('mouseleave', () => (isDraw = false));

完成作品#

Day08: Fun with HTML5 Canvas

Last updated on