Create a basic drawing web app with JavaScript – Part 3

RMAG news

Create a circle on a canvas with animation that moves vertically and horizontally, forward and back.

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 = 50;

let width = canvas.width;
let height = canvas.height;

let x = 75;
let y = 75;

let horizontal = true;
let vertical = true;

let nIntervalID;

document.querySelector(#redColor).addEventListener(change, (event) => {
let newRedValue = event.target.value;
if (newRedValue >= 0 && newRedValue <= 255) {
redColor = newRedValue;
return;
}

redColor = 0;
});

document.querySelector(#greenColor).addEventListener(change, (event) => {
let newGreenValue = event.target.value;
if (newGreenValue >= 0 && newGreenValue <= 255) {
greenColor = newGreenValue;
return;
}

greenColor = 0;
});

document.querySelector(#blueColor).addEventListener(change, (event) => {
let newBlueValue = event.target.value;
if (newBlueValue >= 0 && newBlueValue <= 255) {
blueColor = newBlueValue;
return;
}

blueColor = 0;
});

document.querySelector(#transparent).addEventListener(change, (event) => {
let newValue = event.target.value;
if (newValue >= 0 && newValue <= 100) {
opacity = (newValue * 1.0) / 100;
return;
}

opacity = 1;
});

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 % width, y % height, radius, 0, Math.PI * 2, false);
ctx.fill();
}

function updateCircleHorizontalPosition() {
if (horizontal) {
x += 1;
return;
}
}

function updateCircleVerticalPosition() {
if (vertical) {
y += 1;
return;
}
}

function moveCircle() {
ctx.clearRect(0, 0, width, height);
createCircle(x, y);
}

function removeInterval() {
clearInterval(nIntervalID);
nIntervalID = null;
}

document.querySelector(#horizontal).addEventListener(click, () => {
removeInterval();
nIntervalID = setInterval(() => {
updateCircleHorizontalPosition();
moveCircle();
}, 10);
});

document.querySelector(#vertical).addEventListener(click, () => {
removeInterval();
nIntervalID = setInterval(() => {
updateCircleVerticalPosition();
moveCircle();
}, 10);
});

document.querySelector(#stop).addEventListener(click, () => {
removeInterval();
});

document.querySelector(#clear).addEventListener(click, () => {
removeInterval();
x = 0;
y = 0;
ctx.clearRect(0, 0, width, height);
});

Result

Leave a Reply

Your email address will not be published. Required fields are marked *