在实现画板前,先明确一下要实现的功能:
1.可以改变画笔的颜色
2.可以改变画笔的大小
3.可以改变画笔的形状
4.可以改变画笔的类型(边框绘制或者填充绘制)
5.清空画布
那么先写出对应的html结构
开始编写js代码,首先创建canvas对象,设置canvas的宽高
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
然后封装一些方法以实现画笔的绘制
//画笔方法
//圆形
function drawByArc(x, y, radius, type) {
context.beginPath()
context.arc(x, y, radius, 0, 2 * Math.PI)
if (type == 'fill')
context.fill()
else
context.stroke()
context.closePath()
}
//正方形
function drawByRic(x, y, radius,type) {
radius *= 2
context.beginPath()
context.rect(x, y, radius, radius)
if (type == 'fill')
context.fill()
else
context.stroke()
context.closePath()
}
//正三角形
function drawByTriangle(x, y, radius,type) {
context.beginPath()
context.moveTo(x, y - radius)
context.lineTo(x + Math.sin(Math.PI / 3) * radius, y + Math.cos(Math.PI / 3) * radius)
context.lineTo(x - Math.sin(Math.PI / 3) * radius, y + Math.cos(Math.PI / 3) * radius)
context.lineTo(x, y - radius)
if (type == 'fill')
context.fill()
else
context.stroke()
context.closePath()
}
接着是监听事件,我们要实现按下移动时会有绘制效果,那么可以通过在canvas的onmousedown事件中封装onmousemove事件对应的方法,当触发onmouseup事件时将该事件取消。
canvas.onmousedown = function() {
this.onmousemove = function(event) {
let left = event.clientX - this.offsetLeft
let top = event.clientY - this.offsetTop
let radius = document.getElementById('radius').value // 设置画笔半径
let type = document.getElementById('type').value // 设置画笔类型
context.fillStyle = document.getElementById('fillColor').value // 设置填充颜色
context.strokeStyle = document.getElementById('strokeColor').value // 设置描边颜色
switch (document.getElementById('shape').value) {
case "arc":
drawByArc(left, top, radius, type);
break
case "ric":
drawByRic(left, top, radius, type);
break;
case "tri":
drawByTriangle(left, top, radius, type);
break;
}
}
this.onmouseup = function() {
this.onmousemove = null
}
}
最后实现清空画布的点击
document.getElementById('clear').onclick = () => {
context.clearRect(0, 0, 400, 400)
}
这样就实现了简单的画板。