You are currently viewing JavaScript Cheat Sheet 11.1.8:JavaScript Graphics

JavaScript Cheat Sheet 11.1.8:JavaScript Graphics

Introduction to JavaScript Graphics

Welcome to the world of JavaScript graphics! In this tutorial, you will learn the basics of programming graphics using JavaScript. We’ll cover fundamental concepts and provide hands-on examples to help you understand how to create interactive graphics using JavaScript.

1. Setting up a Canvas Element in HTML:

To begin creating graphics in JavaScript, you need to set up a canvas element in your HTML file. The canvas element acts as a drawing surface where you can render graphics.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Graphics</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script src="script.js"></script>
</body>
</html>

In this example, we have created a canvas element with an id of “myCanvas” and specified its width and height.

2. Drawing Basic Shapes:

Now, let’s start drawing basic shapes on the canvas using JavaScript.

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

// Drawing a line
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 50);
ctx.strokeStyle = 'red';
ctx.stroke();

// Drawing a rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(100, 100, 150, 100);

// Drawing a circle
ctx.beginPath();
ctx.arc(300, 300, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();

Explanation:

  • getContext('2d') method gets the drawing context for the canvas.
  • beginPath() starts a new path.
  • moveTo(x, y) moves the starting point of the path to the specified (x, y) coordinates.
  • lineTo(x, y) draws a line from the current position to the specified (x, y) coordinates.
  • stroke() draws the path.
  • fillRect(x, y, width, height) draws a filled rectangle.
  • arc(x, y, radius, startAngle, endAngle) creates an arc/curve.
  • fill() fills the current drawing (the circle in this case).

3. Adding Interactivity:

Let’s make the circle change color when clicked.

// script.js
canvas.addEventListener('click', function(event) {
    const mouseX = event.clientX - canvas.offsetLeft;
    const mouseY = event.clientY - canvas.offsetTop;

    if (ctx.isPointInPath(mouseX, mouseY)) {
        ctx.fillStyle = 'yellow';
        ctx.fill();
    }
});

Explanation:

  • addEventListener() attaches an event handler to the canvas.
  • clientX and clientY give the mouse coordinates relative to the browser window.
  • offsetLeft and offsetTop give the position of the canvas relative to the document.
  • isPointInPath(x, y) checks if a point is inside the current path.

4. Animating Graphics:

Now, let’s animate the rectangle to move across the canvas.

// script.js
let x = 0;

function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'blue';
    ctx.fillRect(x, 200, 50, 50);
    x += 1; // Move the rectangle horizontally
}

animate();

Explanation:

  • requestAnimationFrame() schedules a repaint of the canvas for the next animation frame.
  • clearRect(x, y, width, height) clears the specified rectangular area, making it transparent.
  • The rectangle’s position (x) is incremented in each animation frame to create the animation effect.

5. Using Libraries for Advanced Graphics (Optional):

For more complex graphics, you can use libraries like Three.js or PixiJS, which provide higher-level abstractions for 3D and 2D graphics, respectively.

Congratulations! You’ve now learned the basics of programming graphics using JavaScript. Experiment with these concepts to create your own interactive and animated graphics!

Leave a Reply