J

JavaScript Handbook

Clean • Professional

Graphics in JavaScript

2 minute

Graphics in JavaScript

JavaScript provides multiple ways to create graphics in the browser, ranging from simple 2D drawings to complex 3D visualizations. You can use these techniques to draw shapes, create animations, and develop interactive visual content.

Canvas API (2D Graphics)

The Canvas API allows you to draw graphics directly on a <canvas> element in HTML. It’s perfect for 2D shapes, charts, and animations.

Example: Drawing Shapes

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);

// Draw a circle
ctx.beginPath();
ctx.arc(200, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
</script>
  • fillRect(x, y, width, height) → Draw filled rectangle.
  • arc(x, y, radius, startAngle, endAngle) → Draw circles or arcs.
  • stroke() → Draw outlines.

SVG (Scalable Vector Graphics)

SVG is vector-based, which means graphics scale without losing quality. You can manipulate SVG elements with JavaScript and CSS.

Example: Drawing a Circle

<svg width="200" height="200">
  <circle id="myCircle" cx="100" cy="100" r="50" fill="green"/>
</svg>

<script>
const circle = document.getElementById("myCircle");
circle.setAttribute("fill", "orange");  // Change color dynamically
circle.setAttribute("r", 70);           // Change radius
</script>

Advantages:

  • Perfect for icons, logos, and charts.
  • Works with CSS animations.
  • Resolution-independent and scalable.

WebGL (3D Graphics)

WebGL allows hardware-accelerated 3D graphics in the browser. It is low-level, but libraries like Three.js simplify it.

Three.js Example: Basic Cube

<script src="<https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js>"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();
</script>
  • 3D visualizations, games, and simulations.
  • Interactive 3D charts or product viewers.

Libraries for Graphics & Visualization

LibraryTypeUse Case
Chart.js2D chartsBar, line, pie charts
D3.jsData-driven SVGComplex interactive visualizations
Pixi.js2D WebGL graphicsGames, animations, particle effects
Three.js3D graphics3D visualizations and games

 

Article 0 of 0