canvas画板工具
- 好久不见,先来一个美美的么么哒~~~
-
需要注意的几点
-
我们之前说的,不能在css中固定canvas画布的大小,否则绘制和保存下来的图片会变形
-
所以,这里通过setWh()方法来自适应屏幕的画布大小
-
当鼠标移动的时候,需要特殊判断按下之前触发的事件(橡皮擦/画笔)
-
橡皮擦的实质是在要擦除的上方,设置一个透明的图层
-
globalCompositeOperation
:属性设置或返回如何将⼀个新的图像绘制到⽬标(已有)的图像上;属性值为
destination-out
可以模拟橡⽪擦
注意:
save
:保存路径(防⽌画笔样式污染其他图形)
restore
:恢复路径(防⽌画笔样式污染其他图形) -
-
HTML
<canvas id="canvas" width="500" height="400"></canvas> <div id="content"> <button>橡皮擦</button> <button>清空画布</button> <button>画笔</button> <input type="color" id="c"> <button>保存</button> </div>
-
CSS
* { margin: 0; padding: 0; } canvas { position: fixed; left:0; top:0; background: #ffe; overflow: hidden; } #content { position: relative; left: 0; top: 0;
-
JavaScript
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var btnList = document.getElementsByTagName("button"); var c = document.getElementById("c"); var color = "#000"; var type = 1; //设置canvas与屏幕宽高一致 function setWh() { canvas.width = document.documentElement.clientWidth; canvas.height = document.documentElement.clientHeight; } setWh(); // 改变画笔颜色 c.onchange = function (e) { color = e.target.value; } //橡皮擦 btnList[0].onclick = function () { type = 2; } // 清空画布 btnList[1].onclick = function () { ctx.clearRect(0, 0, canvas.width, canvas.height); } //画笔 btnList[2].onclick = function () { type = 1; } // 保存 btnList[3].onclick = function () { let url = canvas.toDataURL('image/jpg'); let a = document.createElement('a'); document.body.appendChild(a); a.href = url; a.download = '我的杰作'; a.target = '_blank'; a.click(); } canvas.onmousedown = function (e) { if (type === 1) { var disx = e.offsetX; var disy = e.offsetY; document.onmousemove = function (e) { ctx.beginPath(); ctx.save(); console.log(color) ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.moveTo(disx, disy); ctx.lineTo(e.clientX, e.clientY); ctx.stroke(); ctx.restore(); ctx.closePath(); disx = e.clientX; disy = e.clientY; } } else if (type === 2) { document.onmousemove = function (e) { ctx.beginPath(); ctx.save(); ctx.globalCompositeOperation = "destination-out"; ctx.arc(e.clientX, e.clientY, 20, 0, 2 * Math.PI); ctx.fill(); ctx.restore(); ctx.closePath(); } } document.onmouseup = function () { document.onmousemove = null; } }
网友评论