From 260bda45a951be70bba4b728abf1e863a09a2526 Mon Sep 17 00:00:00 2001 From: adanrsantos Date: Wed, 9 Oct 2024 23:18:42 -0500 Subject: [PATCH] added drawing to the canvas --- static/canvas.css | 35 ++++++++++++++++++++++++++++- static/canvas.html | 17 ++++++++++++-- static/canvas.js | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 105 insertions(+), 3 deletions(-) diff --git a/static/canvas.css b/static/canvas.css index ad81b73..60a531a 100644 --- a/static/canvas.css +++ b/static/canvas.css @@ -23,14 +23,47 @@ html, body { .canvasCont { display: flex; + flex-direction: column; justify-content: center; align-items: center; - padding: 20px; background-color: yellow; border: solid black; border-radius: 20px; } +.toolbar { + display: flex; + justify-content: space-around; + align-items: center; + border-top: solid black 1px; + width: 100%; + height: 60px; + z-index: 10; +} + +.toolbarItems { + display: flex; + flex-direction: column; + justify-content: center; + font-weight: 900; + color: blue; + text-align: center; + height: 100%; + width: 100px; +} + +.strokePicker { + padding: 0; + margin: 0; + width: 100%; +} + +.strokePicker:hover { + cursor: pointer; +} + + canvas { background-color: lightblue; + margin: 20px; } \ No newline at end of file diff --git a/static/canvas.html b/static/canvas.html index 6152038..f4e0c3a 100644 --- a/static/canvas.html +++ b/static/canvas.html @@ -18,8 +18,21 @@
- +
+
+ + +
+
+ + +
+
+ +
+
- + + \ No newline at end of file diff --git a/static/canvas.js b/static/canvas.js index e69de29..f88c632 100644 --- a/static/canvas.js +++ b/static/canvas.js @@ -0,0 +1,56 @@ +const canvas = document.getElementById("canvas"); +const toolbar = document.getElementById("toolbar"); +const strokePicker = document.getElementById("stroke"); +const ctx = canvas.getContext("2d"); + +const canvasOffsetX = canvas.offsetLeft; +const canvasOffsetY = canvas.offsetTop; + +canvas.width = 850; +canvas.height = 500; + +let isPainting = false; +let lineWidth = 5; +let strokeColor = "#000000"; +let startX; +let startY; + +toolbar.addEventListener("click", e => { + if (e.target.id === "clear"){ + ctx.clearRect(0, 0, canvas.width, canvas.height); + } + + if (e.target.id === "lineWidth"){ + lineWidth = e.target.value; + } +}); + +strokePicker.addEventListener("input", (e) => { + strokeColor = e.target.value; +}); + +const draw = (e) => { + if (!isPainting){ + return; + } + ctx.lineWidth = lineWidth; + ctx.strokeStyle = strokeColor; + ctx.lineCap = "round"; + + ctx.lineTo(e.clientX - canvasOffsetX, e.clientY - canvasOffsetY); + ctx.stroke(); +} + +canvas.addEventListener("mousedown", (e) => { + isPainting = true; + startX = e.clientX; + startY = e.clientY; +}); + +canvas.addEventListener("mouseup", (e) => { + isPainting = false; + ctx.stroke(); + ctx.beginPath(); +}); + +canvas.addEventListener("mousemove", draw); \ No newline at end of file