生活随笔
收集整理的這篇文章主要介紹了
使用canvas制作绘图板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用canvas制作繪圖板
模仿了windows繪圖板,用canvas做了一個繪圖板,可以調整線條顏色,粗細,清除畫布等功能
先看看實際效果圖
以下為代碼:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Canvas
</title><style type="text/css">#canvas {border: 1px solid black;}#choose{width: 300px;}</style>
</head><body><div id="choose"><input type="color" id="color"><select name="" id="lineWidth"><option value="5">--請選擇線條粗細(像素)--
</option><option value="2">2px
</option><option value="5">5px
</option><option value="8">8px
</option><option value="12">12px
</option><option value="15">15px
</option></select><input type="button" id="btnClear" value="清除畫布"></div><canvas id="canvas" width="500" height="500"></canvas>
</body>
<script type="text/javascript">let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); let color = document.getElementById("color");let lineWidth = document.getElementById("lineWidth");let btn = document.getElementById("btnClear");let isDraw = false;canvas.onmousedown = function (){isDraw = true;context.strokeStyle = color.value;context.lineWidth = lineWidth.value;context.beginPath();context.moveTo(event.offsetX,event.offsetY);}canvas.onmousemove = function (){if(isDraw){context.lineTo(event.offsetX,event.offsetY);context.stroke();}}canvas.onmouseup = function (){isDraw = false;}canvas.onmouseout = function(){isDraw = false;}btn.onclick = function(){context.clearRect(0,0,canvas.width,canvas.height);}</script></html>
注:canvas的寬高直接在canvas標簽中寫即可,不要在css中去指定寬高!
總結
以上是生活随笔為你收集整理的使用canvas制作绘图板的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。