實現效果:
可供鼠標畫畫,顏色呈彩虹色漸變,畫筆大小同樣呈漸變效果。
關鍵點:
Canvas:
基本屬性
getContext()
strokeStyle //線條描邊的顏色
fillStyle //填充的顏色
lineCap //筆觸的形狀,有 round | butt | square 圓、平、方。
lineJoin //線條相較的方式,有 round | bevel | miter 圓交、斜交、斜接。
路徑繪製
beginPath() //新建一條路徑
lineTo() //路徑的終點
moveTo() //(此次)繪製操作的起點
stroke() //繪製輪廓
鼠標事件處理:
mousemove
mousedown
mouseup
mouseout
彩虹漸變顏色——HSL
H(hue) 代表色調,取值爲 0~360,專業術語叫色相
S 是飽和度,可以理解爲摻雜進去的灰度值,取值爲 0~1
L 則是亮度,取值也是 0~1,或者百分比。
這之中 H 值從 0 到 360 的變化代表了色相的角度的值域變化,利用這一點就可以實現繪製時線條顏色的漸變了,只需要在它的值超過 360 時恢復到 0 重新累加即可。
html
<canvas id="draw" width="800" height="800"></canvas>
javascript
//獲取 HTML 中的 <canvas> 元素,並設定寬度和高度
var canvas = document.querySelector("#draw");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
//設定 ctx 基本屬性
ctx.strokeStyle = "#999"; //線條描邊的顏色
ctx.lineJoin = "round"; //線條相交的方式
ctx.lineCap = 'round'; //筆觸的形狀
// ctx.globalCompositeOperation = 'multiply';
// ctx.globalCompositeOperation = ' source-over';
let isDrawing = false;
let lastx,lasty;
let direction = true;
let hsl = 0;
// let yan2 = 0;
function draw(e) {
if(!isDrawing) return;
// console.log(e);
// 彩虹漸變顏色——HSL
ctx.strokeStyle = `hsl(${hsl},100%,50%)`;
ctx.beginPath(); //新建一條路徑
ctx.moveTo(lastx,lasty); //(此次)繪製操作的起點
// ctx.moveTo(e.offsetX,e.offsetY);
ctx.lineTo(e.offsetX,e.offsetY); //路徑的終點
ctx.stroke(); //繪製輪廓
[lastx,lasty] = [e.offsetX , e.offsetY];
hsl++;
if(hsl > 360){
hsl = 0;
}
if(ctx.lineWidth >=100 || ctx.lineWidth <= 1){
direction = !direction;
}
if(direction){
ctx.lineWidth++;
}else{
ctx.lineWidth--;
}
//ctx.lineWidth = hsl; //線條的寬度
// yan2++;
// if(yan2 >100){
// yan2 = 0;
// }
}
canvas.addEventListener("mousedown",(e)=>{
isDrawing = true;
[lastx,lasty] = [e.offsetX , e.offsetY];
});
canvas.addEventListener("mousemove",draw);
canvas.addEventListener("mouseup",()=>isDrawing = false);
canvas.addEventListener("mouseout",()=>isDrawing = false);