canvas绘图的强大功能,让人前仆后继的去研究它。代码全部加起来不足百行。还用到了h5中的<input type="color"/>和<input type="range"/>
使得页面更加简洁。
本文只用了鼠标的三个事件 onmousedown onmousemove onmouseup就轻松实现了网页画板的制作。
上代码:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style type="text/css"> 7 #canvas{ 8 border: 1px solid #333; 9 display: block;10 margin:20px auto;11 }12 #color{13 width:100px;14 height:32px;15 position:absolute;16 right:115px;17 top:200px;18 }19 #range{20 width:100px;21 height:32px;22 position:absolute;23 right:115px;24 top:125px;25 }26 #demo{27 background:black;28 width:100px;29 height:5px;30 position:absolute;31 right:115px;32 top:100px;33 }34 </style>35 </head>36 <body background-color="rgba(0,0,0,0.5)">37 <div class="box">38 <h3 align="center">CANVAS制作简单在线画板</h3>39 <canvas id="canvas" width="800" height="600"></canvas>40 <input type="color" id="color"/>41 <div id="demo"></div>42 <input type="range" id="range" min="1" max="10"/>43 </div>44 <script type="text/javascript">45 var canvas=document.getElementById("canvas");46 var cxt=canvas.getContext("2d");47 var color=document.getElementById("color");48 var size=document.getElementById("range");49 var demo=document.getElementById("demo");50 //根据size的变化来使得size上面的线条演示画笔粗细。51 size.onchange=function(){52 demo.style.height=size.value+"px";53 }54 //使得color的颜色与演示线条的颜色一致55 color.onchange=function(){56 demo.style.background=color.value;57 }58 var flag=false;59 //鼠标按下60 canvas.onmousedown= function (e) {61 var mouseX= e.pageX-this.offsetLeft;62 var mouseY= e.pageY-this.offsetTop;63 flag=true;64 cxt.beginPath();65 cxt.lineWidth=size.value;66 cxt.strokeStyle=color.value; 67 cxt.moveTo(mouseX,mouseY);68 };69 //鼠标移动70 canvas.onmousemove= function (e) {71 var mouseX= e.pageX-this.offsetLeft;72 var mouseY= e.pageY-this.offsetTop;73 if(flag){74 75 cxt.lineTo(mouseX,mouseY);76 cxt.stroke();77 }78 }79 //鼠标松开80 canvas.onmouseup= function (e) {81 flag=false;82 }83 </script>84 </body>85 </html>
大家做成后的木模样