JavaScript Graphics

Creating visual elements and animations with JavaScript

🎨 What is JavaScript Graphics?

JavaScript Graphics refers to creating visual elements, animations, and interactive graphics using JavaScript. You can draw shapes, create animations, and build interactive visualizations directly in the browser.


// Simple graphics with JavaScript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw a red circle
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(50, 50, 30, 0, 2 * Math.PI);
ctx.fill();
                                    

Output:

JavaScript Graphics Methods

🖼️

Canvas API

Draw 2D graphics directly on canvas

ctx.fillRect(10, 10, 100, 50);
🎭

SVG Manipulation

Create and modify SVG elements

document.createElementNS('http://www.w3.org/2000/svg', 'circle');
🎬

CSS Animations

Control CSS animations with JS

element.style.transform = 'rotate(45deg)';
🌐

WebGL

3D graphics and complex rendering

canvas.getContext('webgl');

🔹 Basic Canvas Drawing

The HTML5 Canvas element provides a powerful way to draw graphics:

<!-- HTML -->
<canvas id="myCanvas" width="300" height="200"></canvas>

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

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

// Draw a green circle
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(200, 60, 40, 0, 2 * Math.PI);
ctx.fill();
</script>

Output:

🔹 Simple Animation

Create animations using requestAnimationFrame:

let x = 0;

function animate() {
    // Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw moving circle
    ctx.fillStyle = 'orange';
    ctx.beginPath();
    ctx.arc(x, 50, 20, 0, 2 * Math.PI);
    ctx.fill();
    
    // Update position
    x += 2;
    if (x > canvas.width) x = 0;
    
    // Continue animation
    requestAnimationFrame(animate);
}

animate(); // Start animation

Output:

🔹 Interactive Graphics

Make graphics respond to user interactions:

canvas.addEventListener('click', function(event) {
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    // Draw a circle where clicked
    ctx.fillStyle = 'purple';
    ctx.beginPath();
    ctx.arc(x, y, 15, 0, 2 * Math.PI);
    ctx.fill();
});

Output: (Click on the canvas below)

🧠 Test Your Knowledge

Which method is used to get a 2D drawing context from a canvas?