You are currently viewing Creating Random Lines on a Canvas: A Beginner’s Guide

Creating Random Lines on a Canvas: A Beginner’s Guide

In this blog, we’ll explore a simple JavaScript code that uses HTML5 Canvas to draw random lines. This code is perfect for beginners who are just starting with web development and want to understand how to use Canvas for basic graphics.

Setting Up the Canvas

The first part of the code sets up the canvas element. We use window.onload to ensure that the script runs after the page has fully loaded. This is important because we need the canvas element to be available before we can work with it.

javascript

Copy code

window.onload = () => {

    var canvas = document.getElementById("canvas");

    var context = canvas.getContext("2d");

    var width = canvas.width = window.innerWidth;

    var height = canvas.height = window.innerHeight;

};

Here, we retrieve the canvas element from the HTML document using document.getElementById(“canvas”). We then get a 2D drawing context (context) that allows us to draw on the canvas.

Next, we set the width and height of the canvas to match the width and height of the browser window (window.innerWidth and window.innerHeight). This ensures that the canvas covers the entire visible area of the webpage.

Drawing Random Lines

The for loop in the code is responsible for drawing the random lines on the canvas.

javascript

Copy code

for (var i = 0; i < 50; i++) {

    context.beginPath();

    context.moveTo(Math.random() * width, Math.random() * height);

    context.lineTo(Math.random() * width, Math.random() * height);

    context.stroke();

}

In each iteration of the loop (i goes from 0 to 49), we:

Begin a new path (context.beginPath()).

Move the drawing cursor to a random point on the canvas using context.moveTo().

Draw a line from the current cursor position to another random point on the canvas using context.lineTo().

Stroke the path to actually draw the line (context.stroke()). 

Leave a Reply