<svg class="canvas" viewBox="0 0 200 200"></svg>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  display: grid;
  place-items: center;
  background: hsl(0, 0%, 96%);
}

.canvas {
  width: 75vmin;
  height: 75vmin;
  background: hsl(0, 0%, 100%);
}
import { SVG } from "https://cdn.skypack.dev/@svgdotjs/svg.js";

const svg = SVG(".canvas");
const { width } = svg.viewbox();

let x = 0;
let y = 100;
const rectSize = 48;
let dir = 1;

// create a rectangle
const rect = svg.rect(rectSize, rectSize).x(x).cy(y).fill("rebeccapurple");

function animate() {
  // when the rectangle reaches the opposite side of the canvas, reverse its direction
  if (x >= width - rectSize) {
    dir = -1;
  } else if (x <= 0) {
    dir = 1;
  }

  x += dir;

  // update the <rect> element's x value
  rect.x(x);

  // re-run the function over-and-over!
  requestAnimationFrame(animate);
}

// kick off the animation loop
animate();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.