<div class="container">
<div class="options">
<label>画布颜色</label>
<input id="color" type="color" value="#000">
</div>
<div class="options">
<label>画笔粗细</label>
<input id="range" type="range" value="5" min="1" max="50">
</div>
<div class="options">
<button id="clear">清空画布</button>
</div>
<canvas width="1000" height="500"></canvas>
</div>
*{
padding: 0;
margin: 0;
user-select: none;
box-sizing: border-box;
}
html,body{
display: flex;
justify-content: center;
align-items: center;
}
.options{
margin-top: 20px;
align-items: center;
margin-top: 20px;
}
.options input{
outline: 0;
margin-left: 20px;
}
.options button{
outline: 0;
border: 0;
padding: 10px 20px;
border-radius: 3px;
color: #fff;
background: #0d53ff;
cursor: pointer;
}
canvas{
border: 1px solid #ccc;
margin-top: 20px;
}
<script>
const color = document.querySelector('#color');
const range = document.querySelector('#range');
let colorValue = color.value;
rangeValue = range.value;
color.onchange = function(){
colorValue = color.value;
}
range.onchange = function(){
rangeValue = range.value;
}
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let flag = false;
canvas.onmousedown = function (e) {
flag = true;
//DOM.getBoundC 获取元素占document的top,left,bottom,right; width/height
const top = canvas.getBoundingClientRect().top;
const left = canvas.getBoundingClientRect().left;
const mouseX = e.pageX - left;
const mouseY = e.pageY - top;
ctx.strokeStyle = colorValue;
ctx.lineWidth = rangeValue;
ctx.lineCap = 'round' //圆角
ctx.beginPath();
ctx.moveTo(mouseX, mouseY);
console.log("mouseX:",mouseX, 'mouseY:',mouseY);
}
canvas.onmousemove = function (e) {
if(!flag)return;
const top = canvas.getBoundingClientRect().top;
const left = canvas.getBoundingClientRect().left;
const mouseX = e.pageX - left;
const mouseY = e.pageY - top;
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
}
canvas.onmouseup = function () {
flag = false;
}
const clear = document.querySelector('#clear');
clear.onclick = function () {
ctx.clearRect(0, 0, 1000, 500);
}
</script>
![](https://img.haomeiwen.com/i20409039/42441ad2553c888c.PNG)
捕获.PNG
网友评论