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.html | 2 +- index.js | 30 ++++++++++++++++++++++++------ style.css | 12 ++++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index d2fa69c..105506d 100644 --- a/index.html +++ b/index.html @@ -6,7 +6,7 @@ -

+

Click anywhere on the screen to move the robot!

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 diff --git a/style.css b/style.css index f10a42e..8866db5 100644 --- a/style.css +++ b/style.css @@ -1,9 +1,21 @@ body { background: linear-gradient(60deg, skyblue, 70%, blue) no-repeat fixed; background-size: cover; + overflow: hidden; } canvas { background-color: aliceblue; border-radius: 20px; +} + +#instructions { + position: absolute; + left: 20px; + border: 3px dashed orange; + padding: 4px +} + +#instructions:hover { + display: none; } \ No newline at end of file -- cgit v1.2.3