canvas 画板
给大家分享一下canvas画板的小知识 东西很简单 但是有一个需要注意的点。
画板需要实现的功能是:点击画笔,在画板上按下鼠标左键 再抬起 这个完整动作结束之后画一个线条或者形状。实现这个功能需要用到2个 canvas 画板,将2个画板定位在一起,即一个覆盖另外一个,然后将鼠标事件都绑定在上层的画板,在鼠标按下+移动时不停的在上层的画板去画圆+清除,当鼠标抬起时,清除上层画板画的最后一个圆,然后在底层的画板上画出一个相等的圆。这里上层和底层画圆的圆心 半径等等都是相同的,不同的是一个是onmousemove事件,即在移动过程中不停的画圆,一个是 onmouseup 事件,即在鼠标抬起时画一个圆;本例只写了画圆的方法,画线,矩形原理相同,添加颜色只需要将线条颜色改变就 Ok了。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 30px; height: 30px; border: 1px solid black; margin-top: 10px; text-align: center; cursor: default; } span { display: inline-block; } #circle span { width: 20px; height: 20px; margin-top: 5px; border-radius: 100%; border: 1px solid black; } #canvasDown { position: absolute; left: 50px; top: 0; border: 1px solid red; z-index: 5; } #canvasUp { position: absolute; left: 50px; top: 0; border: 1px solid red; z-index: 10; } </style> </head> <body> <div id="circle"><span></span></div> <canvas id="canvasDown" width="800px" height="800px"></canvas> <canvas id="canvasUp" width="800px" height="800px"></canvas> </body> <script> var circleBtn = document.getElementById('circle'); var canvasDown = document.getElementById("canvasDown"); var ctxDown = canvasDown.getContext("2d"); var canvasUp = document.getElementById("canvasUp"); var ctxUp = canvasUp.getContext("2d"); // 画圆 circleBtn.onclick = function() { canvasUp.onmousedown = function(e) { var e = event || window.event; var beginX = e.offsetX; var beginY = e.offsetY; canvasUp.onmousemove = function(e) { var e = event || window.event; var moveX = e.offsetX; var moveY = e.offsetY; ctxUp.clearRect(0, 0, 800, 800); var r = Math.sqrt((moveX - beginX) * (moveX - beginX) + (moveY - beginY) * (moveY - beginY)); ctxUp.beginPath(); ctxUp.arc(beginX, beginY, r, 0, Math.PI * 2); ctxUp.stroke(); ctxUp.closePath(); } canvasUp.onmouseup = function(e) { var e = event || window.event; ctxUp.clearRect(0, 0, 800, 800); var moveX = e.offsetX; var moveY = e.offsetY; var r = Math.sqrt((moveX - beginX) * (moveX - beginX) + (moveY - beginY) * (moveY - beginY)); ctxDown.beginPath(); ctxDown.arc(beginX, beginY, r, 0, Math.PI * 2); ctxDown.stroke(); ctxDown.closePath(); canvasUp.onmousemove = null; } } } </script> </html>