How to create a random art using Canvas HTML5


Canvas is one of the most interesting additions to web pages by HTML5. In some ways, a canvas is like an <img> element. You can add a canvas like this:

<canvas id=”art-board” width=”920px” height=”320px”> </canvas>

And the browser allocates some space in the page for the canvas, with the width and height you have specified.

The HTML5 Canvas element is an HTML tag similar to <div>, <table> that allows user to draw graphics such as lines, squares, circles, etc. via scripting (usually, JavaScript) directly into an allocated canvas block element that appears on the web page. Since you can draw an image on a canvas, you can also to erase and re-draw all or a portion of the canvas image. There are a number of transformations and effects that you can apply to your canvas drawing.

Note: The <canvas> element is just a container for graphics. You need add a script to actually draw the graphics. We will show you how, don’t worry!

In much the same way that you might draw an image using a graphics program like Adobe Photoshop or paint, save it to a file, and load it onto a web page. With canvas you can automate through code and the drawing commands, and immediately see the results on the web page, without the need for an loading an external file. This capability allows you to do many sophisticated things that were once difficult or impossible to do, such as dynamically creating preview images.

Getting Started

Time for you to get this working in your own web page. Go ahead and type in the code below into a new file and then load it in your browser:

Create index.html file and run it on browser:

The HTML: index.html

<!doctype html>
<html lang="en">
    <title>Canvas HTML5</title>
        canvas {
            border: 1px solid black;
    <canvas id="art-board" width="920" height="320"></canvas> 



Blank Canvas

Right now we’ve got a blank canvas with border staring us in the face. Rather than sit here, now we write some JavaScript code, and put a nice art on our canvas.

Canvas API’s

Before we begin, lets checkout some commonly used drawing commands in the canvas API:

  • beginPath()

Start a path segment definition, to be used by a rendering operation, like stroke() or fille()

  • closePath()

Close the path by adding a line segment from the end of the path back to the beginning of the path

  • moveTo(x, y)

Move the registration point for the next relative drawing operation

  • lineTo(x, y)

Create a line path from the current registration point to (x,y)

  • rect(x, y, width, height)

Create a rectangle path where (x,y) is one corner, and the diagonally opposite corner is (x+width,y+height)

  • arc(x, y, radius, startAngleRadians, endAngleRadians, antiClockwiseDirection)

Create a circular arc path (up to a full circle), where (x,y) is the center of the arc, and the arc starts and ends at the given angles (in radians), and moves in either the clockwise or counter-clockwise direction

  • fill()

Fill in the most recently defined path segment

  • stroke()

Stroke (render, make visible) the most recent path segment

  • drawImage(image, …)

Draw an image into the canvas area

  • strokeText(text,…) / fillText(text,…)

Add text to the canvas

  • clearRect(x, y, width, height)

Clear a rectangular portion of the canvas from (x,y) to (x+width,y+height)

  • strokeStyle=[string|object] / fillStyle=[string|object]

Set the color/style attributes for strokes or fills, respectively


Open your text editor and create the following files and test it on browser:

The HTML: index.html

<!doctype html>
<html lang="en">
    <title>Look What I Drew</title>
    <meta charset="utf-8">
    <script src="js/canvas.js"></script>
    <link href="css/style.css" rel="stylesheet" type="text/css"/>
<div class="container">
    <h3>Draw an art and then click on canvas to save the art.</h3>
    <canvas id="art-board" width="920" height="320"></canvas>

            <label for="bgColor">Select background color:</label>
            <select id="bgColor">
                <option value="white" selected="selected">White</option>
                <option value="#2c533d">Green</option>
            <label for="shape">Circles or squares?</label>
            <select id="shape">
                <option value="none" selected="selected">Neither</option>
                <option value="circles">Circles</option>
                <option value="squares">Squares</option>
            <label>Write some text</label>
            <input type="text" id="content">
            <label for="textColor">Select text color:</label>
            <select id="textColor">
                <option value="black" selected="selected">Black</option>
                <option value="#42b373">Green</option>
            <input type="button" id="preview" value="Preview">

The CSS: style.css

* {
    margin: 0 auto;
    padding: 0;

body {
    background-color: #F2F2F2;

.container {
    margin: 0 auto;
    width: 920px;
    padding: 50px 20px;
    background-color: #fff;

h3 {
    text-align: center;

canvas {
    margin: 0 auto;
    border: 1px solid #dadada;

p {
    padding: 10px 20px;

p label {
    width: 200px;
    display: inline-block;

The JavaScript: canvas.js

window.onload = function() {
    var button = document.getElementById("preview");
    button.onclick = previewHandler;

function previewHandler() {
    var canvas = document.getElementById("art-board");
    var context = canvas.getContext("2d");

    /*  We're adding the call to fillBackgroundColor before we draw square or cirle
        So it covers up the previous drawing and gives us a clean background for our new drawing
    fillBackgroundColor(canvas, context);
    var selectObj = document.getElementById("shape");
    var index = selectObj.selectedIndex;
    var shape = selectObj[index].value;
    // Check if the selected shape is square or circle
    if (shape == "squares") {
        for (var squares = 0; squares < 20; squares++) {
            // to draw a square, we are callig a new function drawSquare
            drawSquare(canvas, context);
    } else if (shape == "circles") {
        for (var circles = 0; circles < 20; circles++) {
            // to draw a circle, we are calling a new function drawCircle
            drawCircle(canvas, context);

    drawText(canvas, context);

// Function to create an image in PNG format
function makeImage() {
    var canvas = document.getElementById("art-board");
    canvas.onclick = function () {
        window.location = canvas.toDataURL("image/png");

// Function to draw Square on canvas
function drawSquare(canvas, context) {
    // Here we created a random width and height for a square
    var w = Math.floor(Math.random() * 40);
    var x = Math.floor(Math.random() * canvas.width);
    var y = Math.floor(Math.random() * canvas.height);

    // Just a add a color we are using fillStyle
    context.fillStyle = "#DA4453";

    // Draw the actual square with fillRect
    context.fillRect(x, y, w, w);

// Function to fill background color
function fillBackgroundColor(canvas, context) {
    // Get the selected background color and set it on canvas
    var selectObj = document.getElementById("bgColor");
    var index = selectObj.selectedIndex;
    var bgColor = selectObj.options[index].value;
    context.fillStyle = bgColor;
    context.fillRect(0, 0, 920, 320);

// Function to draw Circle on canvas
function drawCircle(canvas, context) {
    // Here we created a random raidus for circle
    var radius = Math.floor(Math.random() * 40);
    var x = Math.floor(Math.random() * canvas.width);
    var y = Math.floor(Math.random() * canvas.height);
    context.arc(x, y, radius, 0, 360 * Math.PI / 180, true);
    context.fillStyle = "#fac922";

// Function to add static and dynamic text on canvas
function drawText(canvas, context) {
    var selectObj = document.getElementById("textColor");

    // Get content from textfield
    var content = document.getElementById("content").value;
    var index = selectObj.selectedIndex;
    var fgColor = selectObj[index].value;

    // Added some style to text
    context.fillStyle = fgColor;
    context.font = "bold 1em sans-serif";
    context.textAlign = "left";
    // Last two parameters of fillText is X and Y positions for the text.
    context.fillText("I am static text here ! :(", 20, 40);
    context.font = "bold 1em sans-serif";
    context.textAlign = "right";
    context.fillText(content, canvas.width-20, canvas.height-40);



Canvas Art

Note: Some browsers won’t let you grab an image from the canvas. I am using Firefox and it worked. Test yours and do let us know.

Congrats team, we did it! Obviously, there is a lot to do. So don’t stop it here, keep working on it. Happy Programming.!

Try Live Demo:

See the Pen mIJFy by Mohit Bhansali (@mohitbhansali) on CodePen.

Here is the demo video:

Browser Support:

  • Internet Explorer 9 +
  • Firefox 3.0 +
  • Chrome 3.0 +
  • Safari 3.0 +
  • Iphone 1.0 +
  • Android 1.0 +
About Mohit Bhansali

A hyperactive mind with a passion for getting acquainted with the latest technology.

Speak Your Mind