1. 程式人生 > >HTML5-簡易Canvas繪圖板

HTML5-簡易Canvas繪圖板

除了canvas以外,還用了一丟丟meta清除頁面快取,color型別和range型別的input控制元件。其他基本就一些滑鼠響應事件了。總之就一個十分簡易的canvas繪圖板。貼個原始碼。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache"> <meta http-equiv="Cache-Control" content="no-cache, must-revalidate"> <meta http-equiv="expires" content="0"> <title>canvas繪圖板</title> <style> canvas{ border:1px dashed black
;}
</style> <script type="text/javascript"> var canvas; var context; window.onload=function(){ canvas=document.getElementById("drawingCanvas"); context=canvas.getContext("2d"); context.fillStyle="rgb(255,255,255)"; context.fillRect(0,0,canvas.width,canvas.height); context.strokeStyle="rgb(0,0,0)"
; context.lineWidth=5; canvas.onmousedown=startDrawing; canvas.onmouseup=stopDrawing; canvas.onmouseout=stopDrawing; canvas.onmousemove=draw; }; var previousColorElement; function changeColor(color,imgElement){ context.strokeStyle=color; imgElement.className="Selected"; if(previousColorElement!=null){ previousColoeElement.className=""; } previousColorElement=imgElement; } var previousThicknessElement; function changeThickness(thickness,imgElement){ context.lineWidth=thickness; imgElement.className="Selected"; if(previousThicknessElement!=null){ previousThicknessElement.className=""; } previousThicknessElement=imgElement; } var isDrawing=false; function startDrawing(e){ isDrawing=true; context.beginPath(); context.moveTo(e.pageX-canvas.offsetLeft,e.pageY-canvas.offsetTop); } function draw(e){ if(isDrawing==true){ var x=e.pageX-canvas.offsetLeft; var y=e.pageY-canvas.offsetTop; context.lineTo(x,y); context.stroke(); } } function stopDrawing(){ isDrawing=false; } function clearCanvas(){ context.fillStyle="rgb(255,255,255)"; context.fillRect(0,0,canvas.width,canvas.height); }
</script> </head> <body> <div align="center"> COLOR<input type="color" id="colorSelect" onchange="changeColor(colorSelect.value,this);" value="rgb(255,255,255)"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WIDTH<input type="range" id="widthSelect" onchange="context.lineWidth=widthSelect.value;" min="1" max="20"/ value="5">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <button id="clearCanvas" onclick="clearCanvas();">CLEAR ALL</button> <br /> <canvas id="drawingCanvas" width="800" height="400"></canvas> </div> </body> </html>

大概這個鬼樣子。
canvas繪圖板介面
火狐之類的瀏覽器可以直接右鍵儲存繪製的影象為*.png不過我想的是用填充白色就不用寫橡皮擦了所以整個畫布都是填充了白色,存的*.png並不會有透明背景。