使用canvas製做在線畫板

canvas繪圖的強大功能,讓人前仆後繼的去研究它。代碼所有加起來不足百行。還用到了h5中的<input type="color"/>和<input type="range"/>javascript

使得頁面更加簡潔。css

本文只用了鼠標的三個事件 onmousedown onmousemove onmouseup就輕鬆實現了網頁畫板的製做。html

上代碼:java

 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>

你們作成後的木模樣canvas

相關文章
相關標籤/搜索