最近剛學了canvas,寫個小應用練習下javascript
源代碼css
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>
運行效果如圖html
仍然有一些問題:java
改變瀏覽器位置時實際繪畫位置和鼠標位置有差jquery
滑鼠走動過快會產生斷點ajax
但願學習更多知識之後來改進canvas