最近刚学了canvas,写个小应用练习下
源代码
1 <!DOCTYPE> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>無標題文件</title> 6 <script src="http://Ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 7 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.CSS"> 8 <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script> 9 <script type="text/javascript">10 var drawable=false;11 $(function(){12 $("#drawOnBoard").css({"background-color":$("#backgroundcolorChooser").val()});13 });14 function changeBackgroundColor()15 {16 $("#drawOnBoard").css({"background-color":$("#backgroundcolorChooser").val()});17 }18 function setDrawable(sdrawable)19 {20 drawable=sdrawable;21 }22 function beginDrawPicture(event)23 {24 if(drawable==true)25 {26 var canvas=$("#drawOnBoard");27 canvas=canvas[0];28 var content=canvas.getContext("2d");29 30 var mouseX=event.clientX;31 var mouseY=event.clientY;32 33 content.beginPath();34 35 content.arc(mouseX,mouseY,$("#slider-fill").val()*2,0,Math.PI*2,true);36 37 content.closePath();38 content.fillStyle=$("#pencolorChooser").val();39 content.fill();40 }41 }42 </script>43 <style type="text/css">44 .chooseBar{45 display:inline-block;46 width:200px;47 }48 div.ui-input-text{49 display:inline-block;50 width:270px;51 }52 div.ui-slider{53 display:inline-block;54 width:300px;55 }56 </style>57 </head>58 59 <body>60 <canvas id="drawOnBoard" width="600px" height="600px" onmousedown="setDrawable(true);" onMouseMove="beginDrawPicture(event);" onMouseUp="setDrawable(false);" style="border:5px wheat solid;background-color:white;float:left;"></canvas>61 <div style="float:left;margin-top:50px;margin-left:20px;">62 改变画笔颜色:<input type="color" id="pencolorChooser" class="chooseBar"/>63 <br/>64 改变画板颜色:<input type="color" id="backgroundcolorChooser" value="#ffffff" onChange="changeBackgroundColor();" class="chooseBar"/>65 <br/>66 改变画笔大小:<input type="range" name="slider-fill" id="slider-fill" value="5" min="1" max="10" step="1" data-highlight="true" class="chooseBar">67 </div>68 </body>69 </html>
运行效果如图
仍然有一些问题:
改变浏览器位置时实际绘画位置和鼠标位置有差
滑鼠走动过快会产生断点
希望学习更多知识以后来改进
新闻热点
疑难解答