HTML5 圖畫板
本文介紹如何使用HTML5來創建一個圖畫板。通過使用鼠標在畫布上繪畫,你可以創建你自己的繪畫作品。下面是代碼實現:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML5 圖畫板</title> <script> window.onload = function() { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var mouse = {x: 0, y: 0}; var paint = false; canvas.onmousedown = function(e) { paint = true; mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; }; canvas.onmouseup = function() { paint = false; }; canvas.onmousemove = function(e) { if (paint) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; context.beginPath(); context.moveTo(mouse.x, mouse.y); context.lineTo(x, y); context.stroke(); mouse.x = x; mouse.y = y; } }; }; </script> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>
以上代碼中,我們使用了HTML5中的canvas標簽來創建畫布。我們使用了JavaScript中的鼠標事件來捕捉鼠標在畫布上的操作,以實現繪畫功能。具體實現可以參考代碼中的注釋。
有了這個HTML5圖畫板,你可以在網頁上畫出自己的絕妙畫作!