Create a basic drawing web app with JavaScript - Part 1
Chinwendu Agbaetuo
Posted on April 19, 2024
Create a basic drawing application - that draws circles, using a canvas element with a click handler. The handler will monitor clicks on the canvas, triggering a function to draw a circle at the clicked position. Additionally, include input boxes for users to adjust the R, G, and B components of the color, these will need to range from 0 to 255, a slider to adjust the radius of the circle drawn and finally a button to clear the canvas.
Solution
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
let redColor = 0;
let greenColor = 0;
let blueColor = 0;
let opacity = 1;
let radius = 100;
let width = canvas.width;
let height = canvas.height;
// handle red value
document.querySelector("#redColor").addEventListener("change", (event) => {
let newRedValue = event.target.value;
if (newRedValue >= 0 && newRedValue <= 255) {
redColor = newRedValue;
return;
}
redColor = 0;
});
// handle green value
document.querySelector("#greenColor").addEventListener("change", (event) => {
let newGreenValue = event.target.value;
if (newGreenValue >= 0 && newGreenValue <= 255) {
greenColor = newGreenValue;
return;
}
greenColor = 0;
});
// handle blue value
document.querySelector("#blueColor").addEventListener("change", (event) => {
let newBlueValue = event.target.value;
if (newBlueValue >= 0 && newBlueValue <= 255) {
blueColor = newBlueValue;
return;
}
blueColor = 0;
});
// handle opacity
document.querySelector("#transparent").addEventListener("change", (event) => {
let newValue = event.target.value;
if (newValue >= 0 && newValue <= 100) {
opacity = (newValue * 1.0) / 100;
return;
}
opacity = 1;
});
// handle radius
document.querySelector("#radius").addEventListener("change", (event) => {
let newRadiusValue = event.target.value;
radius = newRadiusValue * 100;
});
function createCircle(x, y) {
ctx.fillStyle = `rgba(${redColor}, ${greenColor}, ${blueColor}, ${opacity})`;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.fill();
}
canvas.addEventListener("click", (event) => {
createCircle(event.offsetX, event.offsetY);
});
document.querySelector("#clear").addEventListener("click", () => {
ctx.clearRect(0, 0, width, height);
});
Result
Continuation
Checkout Part 2
💖 💪 🙅 🚩
Chinwendu Agbaetuo
Posted on April 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.