canvas畫板功能,可以寫寫畫畫,直接複製貼上就可以使用了
阿新 • • 發佈:2018-11-10
<!DOCTYPE html> <html> <head> <title>畫筆功能DEMO</title> <meta charset="utf-8"> </head> <style type="text/css"> .drawColor{ position: absolute; top:10px; z-index: 999; } *{ margin:0; padding:0; } input{ width:100px; border:none; border-radius: 5px; border:1px double #999; background-color: #282923; color:#FFF; cursor:pointer; transition: all 0.5s; } input:hover{ transform: scale(1.05); } #red{ color:red; } #green{ color:green; } #blue{ color:blue; } #clear{ font-weight: bold; } </style> <body> <canvas width="1920" height="1080" id="canvas"> <span>不支援canvas,給使用者判定</span> </canvas> <div class="drawColor"> <input type="button" value="紅畫筆" id="red"> <input type="button" value="綠畫筆" id="green"> <input type="button" value="藍畫筆" id="blue"> <input type="button" value="重置顏色" id="default"> <input type="button" value="清除畫布" id="clear"> </div> <script type="text/javascript"> window.onload = function(){ var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth;//canvas的寬高定於螢幕寬高,WHauto; canvas.height = window.innerHeight;//canvas的寬高定於螢幕寬高,WHauto; var ctx = canvas.getContext("2d");//獲取上下文 var oInput = document.getElementsByTagName("input");//獲取顏色選擇按鈕 for(var i=0;i<oInput.length;i++){ oInput[i].onclick = function(){ var ID = this.getAttribute('id'); switch(ID){ case 'red': ctx.strokeStyle = 'red'; break; case 'green': ctx.strokeStyle = 'green'; break; case 'blue': ctx.strokeStyle = 'blue'; break; case 'default': ctx.strokeStyle = 'black'; break; case 'clear': ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight); break; } } }//選擇不同的按鈕執行不同的strokeStyle draw();//繪製線條函式 function draw(){ canvas.onmousedown = function(ev){ var ev = ev || event;//相容火狐 var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//獲取滾動條滾動距離 ctx.beginPath();//上下文繪製路徑方法開始 ctx.moveTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop+scrollTop); document.onmousemove = function(ev){ var ev = ev || event;//相容火狐 ctx.lineTo(ev.clientX - canvas.offsetLeft,ev.clientY - canvas.offsetTop+scrollTop);//路徑x,y隨著滑鼠move跟隨 ctx.stroke();//上下文結束路徑方法 } document.onmouseup = function(ev){ document.onmousemove = document.onmouseup = null; ctx.closePath();//結束路徑 } } } } </script> </body> </html>
難點主要:
1.相容火狐
2.獲取滑鼠相對canvas移動距離(scrollTop也要算進去)
3.事件邏輯
歡迎聯絡郵箱:[email protected]