added drawing to the canvas

This commit is contained in:
adanrsantos 2024-10-09 23:18:42 -05:00
parent dcb9e37dc8
commit 260bda45a9
3 changed files with 105 additions and 3 deletions

View file

@ -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;
}

View file

@ -18,8 +18,21 @@
</div>
<div class="canvasCont">
<canvas id="canvas" width="850" height="500" style="border:1px solid #000000;" alt="canvas"></canvas>
<div id="toolbar" class="toolbar">
<div class="toolbarItems">
<label for="stroke">Strokes</label>
<input id="stroke" name="stroke" type="color" class="strokePicker">
</div>
<div class="toolbarItems">
<label for="lineWidth">Line Width</label>
<input id="lineWidth" name="lineWidth" type="number" value="5" min="1" max="10">
</div>
<div class="toolbarItems">
<button id="clear">Clear</button>
</div>
</div>
</div>
</div>
<script src="./canvas.js"></script>
</body>
</html>

View file

@ -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);