实现画笔和橡皮的功能
Posted bgwhite
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现画笔和橡皮的功能相关的知识,希望对你有一定的参考价值。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>鼠标画线和方块移动</title> </head> <style> * {margin: 0;padding: 0;} body {background-color: #000;} #c1 {background-color: #fff} .active {background-color: red;color: #fff} </style> <body> <canvas id="c1" width="400" height="400"></canvas> <input class="active" type="button" value="画笔"> <input type="button" value="橡皮擦"> <script> var oC = document.getElementById(‘c1‘); var aInput = document.getElementsByTagName("input"); var num = 0; for(var i=0;i<aInput.length;i++) { aInput[i].index = i; aInput[i].onclick = function () { for(var j= 0;j<aInput.length;j++) { aInput[j].className = ""; } this.className = "active"; num = this.index; } } var ctx = oC.getContext("2d"); oC.onmousedown = function(ev) { var x = ev.pageX - oC.offsetLeft; var y = ev.pageY - oC.offsetTop; ctx.beginPath(); ctx.moveTo(x,y); oC.onmousemove = function(ev) { var x = ev.pageX - oC.offsetLeft; var y = ev.pageY - oC.offsetTop; if(num ==0) { ctx.lineTo(x,y); ctx.stroke(); } else if(num ==1) { ctx.clearRect(x,y,20,20); } }; oC.onmouseup = function (ev) { oC.onmousemove = null; oC.onmouseup = null; ctx.closePath(); }; return false; } </script> </body> </html>
以上是关于实现画笔和橡皮的功能的主要内容,如果未能解决你的问题,请参考以下文章