画板实现的效果:可以切换画笔的粗细,颜色,还可以使用橡皮擦,还可以清除画布,然后将画的内容保存下载成一张图片:
具体用到的canvas功能有:画笔的粗细调整lineWidth,开始一个新的画笔路径beginPath,结束一个画笔路径closePath,这个可以保证不影响之前画的效果,重新开始一个画笔路径。 还有橡皮擦使用的ctx.globalCompositeOperation = 'destination-out'属性,清空画布使用的:ctx.clearRect(0, 0, canvas.width, canvas.height),保存图片使用的是let url = canvas.toDataURL('image/png')。
完整的代码如下:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>像素操作</title><style>.active {background-color: #f2a1a1;}</style></head><body><div>创建一个画布,可以使用画笔随意画画</div><div style="width: 800px; margin-top: 6px"><button class="bold">粗线条</button><button class="thin">细线条</button><input id="color" type="color" /><button class="del">橡皮擦</button><button class="clear">清空画布</button><button class="save">保存图片</button><hr /><canvas id="myCanvas" width="800" height="600"></canvas></div><script>// 获取画布const canvas = document.getElementById('myCanvas')// 获取画笔const ctx = canvas.getContext('2d')// 让画笔的拐弯处更加圆润,没有锯齿感ctx.lineCap = 'round'ctx.lineJoin = 'round'// 获取控制按钮const bold = document.querySelector('.bold')const thin = document.querySelector('.thin')const color = document.querySelector('#color')const del = document.querySelector('.del')const clear = document.querySelector('.clear')const save = document.querySelector('.save')// 添加点击事件bold.onclick = function () {ctx.lineWidth = 20bold.classList.add('active')thin.classList.remove('active')del.classList.remove('active')clear.classList.remove('active')save.classList.remove('active')}thin.onclick = function () {ctx.lineWidth = 5thin.classList.add('active')bold.classList.remove('active')del.classList.remove('active')clear.classList.remove('active')save.classList.remove('active')}color.onchange = function (e) {console.log('颜色改变了:', e.target.value)ctx.strokeStyle = e.target.value}del.onclick = function () {console.log('橡皮擦')ctx.globalCompositeOperation = 'destination-out'ctx.lineWidth = 30del.classList.add('active')bold.classList.remove('active')thin.classList.remove('active')clear.classList.remove('active')save.classList.remove('active')}clear.onclick = function () {console.log('清空画布')ctx.clearRect(0, 0, canvas.width, canvas.height)}// 保存图片save.onclick = function () {console.log('保存图片')let url = canvas.toDataURL('image/png')let a = document.createElement('a')a.href = urla.download = 'canvas.png'a.click()}// 监听画布画画事件let mouseDown = false// 鼠标按下将变量设置为truecanvas.onmousedown = function (e) {ctx.beginPath()mouseDown = truectx.moveTo(e.offsetX, e.offsetY)}// 鼠标抬起将变量设置为falsecanvas.onmouseup = function () {mouseDown = falsectx.closePath()ctx.globalCompositeOperation = 'source-over'}canvas.onmouseleave = function () {mouseDown = falsectx.closePath()}// 鼠标移动canvas.onmousemove = function (e) {if (mouseDown) {console.log('鼠标移动')ctx.lineTo(e.offsetX, e.offsetY)ctx.stroke()}}</script></body>
</html>