用canvas實現一個簡易的塗鴉畫板
阿新 • • 發佈:2019-02-03
這是一個簡單的用H5中的新特性canvas寫的畫板它實現了選擇本機圖片繪製在瀏覽器上,並可以用畫筆塗鴉最後可以儲存塗鴉.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> canvas{border:1px solid green;} </style> </head> <body> 選擇圖片:<input id="file" type="file"> <button onclick="restuya()">重新塗鴉</button> <button onclick="saveTu();">儲存圖片</button> <hr> <canvas id="canvas" width="1105" height="500"> 您的破瀏覽器不相容,請升級! </canvas> <hr> <div id="res"></div> <script type="text/javascript"> // 獲取 canvas 物件 var canvas = document.getElementById('canvas'); // 獲取繪圖環境 var ctx = canvas.getContext('2d'); var last = null; var file = document.getElementById('file'); // 檔案物件 var filedata = null; // 滑鼠按下 canvas.onmousedown = function(){ // 在滑鼠按下後觸發滑鼠移動事件 canvas.onmousemove = move; } // 滑鼠擡起取消滑鼠移動的事件 canvas.onmouseup = function(){ canvas.onmousemove = null; last = null; } // 滑鼠移出畫布時 移動事件也要取消。 canvas.onmouseout = function(){ canvas.onmousemove = null; last = null; } // 滑鼠移動函式 function move(e){ // console.log(e.offsetX); if(last != null){ ctx.beginPath(); ctx.moveTo(last[0],last[1]); ctx.lineTo(e.offsetX,e.offsetY); ctx.stroke(); } // 第一次觸發這個函式,只做一件事,把當前 滑鼠的 x , y 的位置記錄下來 // 做下一次 線段的 起始點。 last = [e.offsetX,e.offsetY]; } // 當檔案域內容發生改變時觸發函式 file.onchange = function(e){ filedata = e.target.files[0]; // 例項化檔案讀取物件 drawImg(filedata) } // 重新在畫 function restuya(){ ctx.clearRect(0,0,canvas.width,canvas.height); drawImg(filedata) } // 繪製圖片 function drawImg(filedata){ var readFile = new FileReader(); readFile.readAsDataURL(filedata); // 圖片讀取成功 readFile.onload = function(){ // 結果 // console.log(this.result); // this.result; // 第一種方法 var Img = new Image(); Img.src = this.result; Img.onload = function(){ // 根據 圖片的 寬高 來 設定canvas 寬和高 canvas.width = Img.width; canvas.height = Img.height; // console.log(Img.width); // canvas.width = 500; // canvas.width = 500; ctx.drawImage(Img,0,0); } } } // 儲存圖片 function saveTu(){ var saveImage = canvas.toDataURL('image/png'); document.getElementById('res').innerHTML = '<img src="'+saveImage+'">'; } </script> </body> </html>