DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

Create a basic drawing web app with JavaScript - Part 2

Add animation to the circle, so that it reappears at the top-left corner when it reaches the bottom-right corner.

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;

let x = 0;
let y = 0;

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 updateCirclePosition() {
  x += 1;
  y += 1;
}

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

document.querySelector("#start").addEventListener("click", () => {
  nIntervalID = setInterval(() => {
    updateCirclePosition();
    moveCircle();
  }, 10);
});

document.querySelector("#stop").addEventListener("click", () => {
  clearInterval(nIntervalID);
  nIntervalID = null;
});

document.querySelector("#clear").addEventListener("click", () => {
  x = 0;
  y = 0;
  clearInterval(nIntervalID);
  nIntervalID = null;
  ctx.clearRect(0, 0, width, height);
});
Enter fullscreen mode Exit fullscreen mode

Result

Continuation
Checkout Part 3

Top comments (0)