Clean β’ Professional
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.
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 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:
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>
| Library | Type | Use Case |
|---|---|---|
| Chart.js | 2D charts | Bar, line, pie charts |
| D3.js | Data-driven SVG | Complex interactive visualizations |
| Pixi.js | 2D WebGL graphics | Games, animations, particle effects |
| Three.js | 3D graphics | 3D visualizations and games |
Β