Github: https://github.com/MingRay98/singatureBoard-original-JS
說明:
使用原生 JS 、ES6 、Parcel、CodeSandBox 的小專案
不使用vue、react、Angular 框架,且不使用html標籤語法建立元件。
主要用到元件:
<button>、 <canvas> 、 <input>、<a>
主要用到方法為:
//建立Canvas export const createCanvas = (width, height) => { let canvas = document.createElement("canvas"); canvas.id = "signatureCanvas"; canvas.width = width; canvas.height = height; canvas.style.zIndex = 8; canvas.style.border = "1px solid"; return canvas; }; //幫canvas增加事件 export const getGlobalCanvas = () => { globalCanvas = document.getElementById("signatureCanvas"); globalCtx = globalCanvas.getContext("2d"); globalCanvas.addEventListener("mousedown", addDrawPoint, false); globalCanvas.addEventListener("mousemove", drawLine, false); globalCanvas.addEventListener("mouseup", stopDrawing, false); globalCanvas.addEventListener("mouseout", stopDrawing, false); globalCanvas.addEventListener("touchstart", tAddDrawPoint, false); globalCanvas.addEventListener("touchmove", tDrawLine, false); globalCanvas.addEventListener("touchend", tStopDrawing, false); globalCanvas.addEventListener("touchcancel", tStopDrawing, false); }; const addDrawPoint = event => { drawing = true; x = event.offsetX; y = event.offsetY; }; const drawLine = event => { if (drawing) { globalCtx.lineWidth = 3; globalCtx.beginPath(); globalCtx.moveTo(x, y); globalCtx.lineTo(event.offsetX, event.offsetY); globalCtx.stroke(); x = event.offsetX; y = event.offsetY; } }; const stopDrawing = event => { drawing = false; }; //t = touch 觸控事件需要扣除 canvas的偏移 const tAddDrawPoint = event => { drawing = true; console.log(event.targetTouches[0]); x = event.targetTouches[0].pageX - globalCanvas.offsetLeft; y = event.targetTouches[0].pageY - globalCanvas.offsetTop; }; const tDrawLine = event => { if (drawing) { globalCtx.lineWidth = 3; globalCtx.beginPath(); globalCtx.moveTo(x, y); globalCtx.lineTo( event.targetTouches[0].pageX - globalCanvas.offsetLeft, event.targetTouches[0].pageY - globalCanvas.offsetTop ); globalCtx.stroke(); x = event.targetTouches[0].pageX - globalCanvas.offsetLeft; y = event.targetTouches[0].pageY - globalCanvas.offsetTop; } }; const tStopDrawing = event => { drawing = false; };
//下載的方法 const download = () => { const link = document.createElement("a"); link.download = "signature.png"; link.href = document.getElementById("signatureCanvas").toDataURL(); link.click(); };
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記