const canvas = document.getElementById('drawing-board'); const ctx = canvas.getContext('2d'); const canvasOffsetX = canvas.offsetLeft; const canvasOffsetY = canvas.offsetTop; canvas.width = window.innerWidth - canvasOffsetX * 2; canvas.height = window.innerHeight - canvasOffsetY * 2; let isPainting = false; let lineWidth = 5; let strokeColor = "skyblue" let drawings = []; ctx.strokeStyle = strokeColor; const draw = (x, y) => { if (!isPainting) { return; } ctx.lineWidth = lineWidth; ctx.lineCap = 'round'; ctx.lineTo(x - canvasOffsetX, y - canvasOffsetY); drawings.push({x : (x - canvasOffsetX)/canvas.width, y : (y - canvasOffsetY)/canvas.height}); ctx.stroke(); } canvas.addEventListener('mousedown', (e) => { isPainting = true; }); canvas.addEventListener('mouseup', (e) => { isPainting = false; drawings.push({x : -1, y : -1}) ctx.stroke(); ctx.beginPath(); }); canvas.addEventListener('mousemove', (e) => draw(e.clientX, e.clientY)); canvas.addEventListener('touchstart', (e) => { console.log(e); isPainting = true; }); canvas.addEventListener('touchend', (e) => { isPainting = false; drawings.push({x : -1, y : -1}) ctx.stroke(); ctx.beginPath(); }); canvas.addEventListener('touchmove', (e) => draw(e.targetTouches[0].clientX, e.targetTouches[0].clientY)); function redrawCanvas() { canvas.width = window.innerWidth - canvasOffsetX * 2; canvas.height = window.innerHeight - canvasOffsetY * 2; ctx.strokeStyle = strokeColor; ctx.lineWidth = lineWidth; ctx.lineCap = 'round'; drawings.forEach(element => { if (element.x >= 0 && element.y >= 0){ ctx.lineTo(element.x * canvas.width, element.y * canvas.height); ctx.stroke(); } else { ctx.stroke(); ctx.beginPath(); } }); } window.onresize = redrawCanvas;