From c46a491374a9bcf0d88b24b8ce4cf30a996b25ce Mon Sep 17 00:00:00 2001 From: Martial Simon Date: Thu, 15 Feb 2024 14:52:44 +0200 Subject: feat: handle resize event --- index.js | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) (limited to 'index.js') diff --git a/index.js b/index.js index 3ef5dd2..fabec5f 100644 --- a/index.js +++ b/index.js @@ -9,12 +9,11 @@ canvas.height = window.innerHeight - canvasOffsetY * 2; let isPainting = false; let lineWidth = 5; -let startX; -let startY; -ctx.strokeStyle = "skyblue"; +let strokeColor = "skyblue" +let drawings = []; +ctx.strokeStyle = strokeColor; const draw = (e) => { - console.log(e); if (!isPainting) { return; } @@ -23,8 +22,8 @@ const draw = (e) => { ctx.lineCap = 'round'; ctx.lineTo(e.pageX - canvasOffsetX, e.pageY - canvasOffsetY); + drawings.push({x : (e.pageX - canvasOffsetX)/canvas.width, y : (e.pageY - canvasOffsetY)/canvas.height}); ctx.stroke(); - } canvas.addEventListener('mousedown', (e) => { isPainting = true; @@ -32,8 +31,27 @@ canvas.addEventListener('mousedown', (e) => { canvas.addEventListener('mouseup', (e) => { isPainting = false; + drawings.push({x : -1, y : -1}) ctx.stroke(); ctx.beginPath(); }); -canvas.addEventListener('mousemove', draw); \ No newline at end of file +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; \ No newline at end of file -- cgit v1.2.3