Fun with HTML5 Canvas
Step 1. HTML 新增 canvas
<canvas id="draw" width="800" height="800"></canvas>
Step 2. 建立畫布
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d'); //2d or 3d
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
ctx的設定
🔍 參考連結:HTML Canvas Reference
ctx.strokeStyle = "#FF0000";
線段顏色設定ctx.lineCap = "round";
:線段圓角/方角/符合邊緣ctx.lineJoin = "round";
:線段轉折圓角/平切/尖角ctx.lineWidth = 10;
:線段寬度
狀態參數設定
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;
canvas設定
canvas.addEventListener("mousemove",draw);
canvas.addEventListener("mousedown",()⇒{
isDrawing=true;
[lastX, lastY] = [e.offsetX, e.offestY];
});
canvas.addEventListener("mouseup",()⇒isDrawing=false);
canvas.addEventListener("mouseout",()⇒isDrawing=false);
draw function-畫線
function draw(e){
if (!isDrawing) return;
ctx.beginPath();//開始or重置畫圖
//start from
ctx.moveTo(lastX, lastY);
//go to
ctx.lineTo(e.offsetX, e.offestY);
ctx.stroke();//畫線
[lastX, lastY] = [e.offsetX, e.offestY];
}
draw function-顏色和線段粗細
- HSL參考:Mothereffing HSL
function draw(e){
if (!isDrawing) return;
ctx.strokeStyle=`hsl(${hue}, 100%, 50%)`;
ctx.beginPath();//開始or重置畫圖
//start from
ctx.moveTo(lastX, lastY);
//go to
ctx.lineTo(e.offsetX, e.offestY);
ctx.stroke();//畫線
[lastX, lastY] = [e.offsetX, e.offestY];
//顏色
hue++;
if(hue >=360){
hue = 0;
}
//線段
if(ctx.lineWidth >= 100 || ctx.lineWidth < 1){
direction = !direction;
}
if(direction){
ctx.lineWidth++;
}else{
ctx.lineWidth--;
}
}
ctx的設定-混合模式
ctx.globalCompositeOperation = 'multiply';
🔍 參考連結:CanvasRenderingContext2D.globalCompositeOperation — Web APIs | MDN