js+canvas實現畫板功能
本文實例為大家分享了js+canvas實現畫板功能的具體代碼,供大家參考,具體內容如下
1.實現了畫圖,改變畫筆粗細,改變畫筆顏色,清屏功能
<!DOCTYPE html><html> <head> <meta charset='utf-8' /> <title>畫板</title> <link rel='shortcut icon' type='image/x-icon' href='http://www.aoyou183.cn/bcjs/img/an.ico' /> <link rel='stylesheet' type='text/css' href='http://www.aoyou183.cn/bcjs/css/drow.css' /> </head> <body> <canvas height='660px'></canvas> <div class='tool'> 畫筆顏色:<input type='color' name='color1' /><br /> 畫筆粗細:<input type='range' name='range1' id='range1'min='1' max='20'/><br /> <button class='btn'>清屏</button> </div> </body> <script src='http://www.aoyou183.cn/bcjs/js/drow.js' type='text/javascript' charset='utf-8'></script></html>
*{ margin: 0; padding: 0; text-align: left; -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none;}#mycanvas{ border: 2px solid deepskyblue;}.tool{ width: 260px; height: 100%; position: fixed; right: 0; top: 0; background-color: #CCCCCC;}
//獲取對象var mycanvas = document.getElementById('mycanvas');var color1 = document.getElementById('color1');var range1 = document.getElementById('range1');var btn = document.getElementsByClassName('btn')[0];var contxt = mycanvas.getContext('2d');btn.onclick=function () { contxt.clearRect(0,0,1200,660);}var flag = false;var x = 0, y = 0;// 鼠標點下事件mycanvas.onmousedown = function(event) { flag = true; // 獲取鼠標點下的開始位置 var x = event.clientX - mycanvas.offsetLeft; var y = event.clientY - mycanvas.offsetTop; contxt.beginPath(); // 開始新建路徑 contxt.strokeStyle = color1.value; // 獲得顏色賦值給畫筆 contxt.lineCap='round'; contxt.lineWidth = range1.value; // 獲得畫筆寬度賦值給畫筆 contxt.moveTo(x, y); // 開始位置 }// 鼠標移動事件mycanvas.onmousemove = function(event) { // 獲取鼠標在移動的位置 var mX = event.clientX - mycanvas.offsetLeft; var mY = event.clientY - mycanvas.offsetTop; if (flag) { contxt.lineTo(mX, mY); // 移動途中和結束位置 contxt.stroke(); // 結束渲染畫布 } }// 鼠標松開事件mycanvas.onmouseup = function() { flag = false;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: