做移动网站优化快速,易物网网站建设管理,三只松鼠有趣的软文,公司邮箱手机怎么登录画板实现的效果#xff1a;可以切换画笔的粗细#xff0c;颜色#xff0c;还可以使用橡皮擦#xff0c;还可以清除画布#xff0c;然后将画的内容保存下载成一张图片#xff1a;
具体用到的canvas功能有#xff1a;画笔的粗细调整lineWidth#xff0c;开始一个新的画笔…画板实现的效果可以切换画笔的粗细颜色还可以使用橡皮擦还可以清除画布然后将画的内容保存下载成一张图片
具体用到的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 langenheadmeta charsetUTF-8 /meta nameviewport contentwidthdevice-width, initial-scale1.0 /title像素操作/titlestyle.active {background-color: #f2a1a1;}/style/headbodydiv创建一个画布可以使用画笔随意画画/divdiv stylewidth: 800px; margin-top: 6pxbutton classbold粗线条/buttonbutton classthin细线条/buttoninput idcolor typecolor /button classdel橡皮擦/buttonbutton classclear清空画布/buttonbutton classsave保存图片/buttonhr /canvas idmyCanvas width800 height600/canvas/divscript// 获取画布const canvas document.getElementById(myCanvas)// 获取画笔const ctx canvas.getContext(2d)// 让画笔的拐弯处更加圆润没有锯齿感ctx.lineCap roundctx.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-outctx.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.pnga.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