带有简单的画笔粗度选择、颜色选择、画笔展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<div class="controls">
<label for="penwidth">PenWidth:</label>
<input id="penwidth" type="range" name="penwidth" min="1" max="50" value="1" data-sizing="px">
<p> </p>
<label for="pencolor">PenColor:</label>
<input id="pencolor" type="color" name="pencolor" value="black">
</div>
<canvas id="pentest" width="50" height="50" style="border:black 3px solid" ></canvas>
<button>ClearUp</button>
<canvas id="draw" width="800" height="800"></canvas>
<script>
const canvas=document.querySelector("#draw");
const displaycanvas=document.querySelector("#pentest");
const ctx=canvas.getContext("2d");
const ctxdisplay=displaycanvas.getContext("2d");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight-100;
canvas.style.border="rgb(10,31,21) solid 5px";
canvas.style.marginTop="5px";
//画笔初值属性设置
ctxdisplay.strokeStyle="#BADASS";
ctxdisplay.lineJion="round";
ctxdisplay.lineCap="round";
ctxdisplay.lineWidth=1;
ctx.strokeStyle="#BADASS";
ctx.lineJion="round";
ctx.lineCap="round";
ctx.lineWidth = 20;
//画笔粗度颜色展示
ctxdisplay.beginPath();
ctxdisplay.moveTo(0, 0);
ctxdisplay.lineTo(25, 25);
ctxdisplay.stroke();
const inputs=document.querySelectorAll(".controls input");
function update(){
switch(this.id){
case "penwidth":
ctxdisplay.lineWidth=parseInt(this.value);
ctx.lineWidth=parseInt(this.value);
break;
case "pencolor":
ctxdisplay.strokeStyle=this.value;
ctx.strokeStyle=this.value;
break;
}
ctxdisplay.clearRect(0,0,displaycanvas.width,displaycanvas.height);
ctxdisplay.beginPath();
ctxdisplay.moveTo(0, 0);
ctxdisplay.lineTo(25, 25);
ctxdisplay.stroke();
}
inputs.forEach(input=>input.addEventListener("change",update));
inputs.forEach(input=>input.addEventListener("mousemove",update));
//绘制部分
let isDrawing=false;
let lastX=0;
let lastY=0;
function draw(e){
if(!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX,lastY);
ctx.lineTo(e.offsetX,e.offsetY);
ctx.stroke();
[lastX,lastY]=[e.offsetX,e.offsetY];
}
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);
//清除画布
const btn=document.querySelector("button");
btn.onclick=function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
</script>
<style>
html, body {
margin: 0;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 20px;
text-align: center;
}
.controls{
display: flex;
flex:1;
justify-content:center;
align-items: center;
}
canvas{
transition: all 0.2s ease;
}
button{
position: absolute;
right: 300px;
top:110px;
font-size: 15px;
}
</style>
</body>
</html>
效果展示: