JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box">
a
<canvas id="cv" width="300" height="80" class="fore"></canvas>
</div>
CSS
.box {
position: relative;
width: 300px;
height: 80px;
line-height: 80px;
background: #fff;
text-align: center;
font-size: 28px;
}
.fore {
position: absolute;
top: 0;
left: 0;
}
JavaScript
var cv = document.getElementById('cv'),
ctx = cv.getContext('2d'),
r = 2; // 点击显示半径为 2 的范围
ctx.fillStyle = '#999';
ctx.rect(0, 0, 300, 80);
ctx.fill();
cv.onmousedown = function(e){
var x1 = e.clientX;
var y1 = e.clientY;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.lineWidth = r * 2;
ctx.globalCompositeOperation = "destination-out";
ctx.save();
ctx.beginPath()
ctx.arc(x1,y1,1,0,2*Math.PI);
ctx.fill();
ctx.restore();
cv.onmousemove = function(e) {
var x2 = e.clientX;
var y2 = e.clientY;
ctx.save();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
ctx.restore();
x1 = x2;
y1 = y2;
}
cv.onmouseup = function(e) {
cv.onmousemove = null;
}
}