<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.wrap {
display: flex;
gap: 20px;
margin-bottom: 20px;
canvas {
border: 1px solid #008c8c;
}
img {
width: 600px;
height: 400px;
background: pink;
}
}
</style>
</head>
<body>
<div class="wrap">
<canvas width="600" height="400"></canvas>
<img src="" alt="" />
</div>
<div>
<button id="clearCvs">清空画布</button>
<span>画笔颜色:</span>
<input type="color" id="penColor" />
<span>画笔粗细:</span>
<input type="range" min="1" max="10" id="penWidth" />
<button id="saveCvs">保存图片</button>
</div>
<script>
/*
1. 实现签名效果,转换为图片
2. 通过canvas.toDataURL() 转换为图片
3. 监听鼠标mousedown、mousemove、mouseup事件
*/
const doms = {
img: document.querySelector('img'),
clearCvs: document.querySelector('#clearCvs'),
penColor: document.querySelector('#penColor'),
penWidth: document.querySelector('#penWidth'),
saveCvs: document.querySelector('#saveCvs'),
};
// 控制是否正在画
let isDrawing = false;
class CanvasEvent {
constructor(cvs) {
this.cvs = cvs;
this.ctx = cvs.getContext('2d');
this.cvs.addEventListener('mousedown', this.mousedown.bind(this));
this.cvs.addEventListener('mousemove', this.mousemove.bind(this));
this.cvs.addEventListener('mouseup', this.mouseup.bind(this));
}
mousedown(e) {
isDrawing = true;
this.ctx.beginPath();
this.ctx.moveTo(e.offsetX, e.offsetY);
}
mousemove(e) {
if (isDrawing) {
this.ctx.lineTo(e.offsetX, e.offsetY);
this.ctx.stroke();
}
}
mouseup(e) {
isDrawing = false;
}
}
const cvs = document.querySelector('canvas');
const c1 = new CanvasEvent(cvs);
// 清空画布
doms.clearCvs.onclick = function () {
c1.ctx.clearRect(0, 0, cvs.width, cvs.height);
};
// 画笔颜色
doms.penColor.onchange = function () {
c1.ctx.strokeStyle = this.value;
};
// 画笔粗细
doms.penWidth.onchange = function () {
c1.ctx.lineWidth = this.value;
};
// 保存图片
doms.saveCvs.onclick = function () {
const img = cvs.toDataURL('image/png');
doms.img.src = img;
// 清空画布
c1.ctx.clearRect(0, 0, cvs.width, cvs.height);
};
</script>
</body>
</html>
移动端监听touch事件即可
822

被折叠的 条评论
为什么被折叠?



