The Wayback Machine - https://web.archive.org/web/20240708014558/https://www.geeksforgeeks.org/how-to-create-3d-cube-using-canvas-in-html5/
Open In App

How to create 3D cube using canvas in HTML5 ?

Last Updated : 12 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see How to create 3D cube using canvas in  HTML5. 

Approach: We will use the canvas element. The HTML Canvas element is used to draw graphics with the help of javascript. It can be used to draw different types of shapes, graphs or create simple and complex animations. Keep in mind that canvas is nothing more than a container for graphics. To draw the graphics, you must use javascript. The canvas default size is 300 x 150 pixels (width x height). Custom sizes, on the other hand, can be specified using the HTML height and width property.

Syntax: 

<canvas width="200" 
        height="100" 
        style="border:4px solid #000;">
</canvas>  

Example: Below is the step-by-step implementation of the 3D cube using canvas.

index.html

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
  
    <title>3D Cube</title>
  
    <style>
        body {
            margin: 0;
        }
  
        canvas {
            display: block;
        }
    </style>
</head>
  
<body>
    <canvas> </canvas>
    <script>
  
        // Constants
        const BACKGROUND_COLOR = "black";
        const CUBE_COLOR = "yellow";
        const POINT_2D = function (x, y) {
            this.x = x;
            this.y = y;
        };
        const POINT_3D = function (x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
        };
  
        // Set up the canvas and context
        var canvas = document.querySelector("canvas");
        var context = canvas.getContext("2d");
  
        // Dimensions
        var h = document.documentElement.clientHeight;
        var w = document.documentElement.clientWidth;
        canvas.height = h;
        canvas.width = w;
  
        // Colors and lines
        context.fillStyle = BACKGROUND_COLOR;
        context.strokeStyle = CUBE_COLOR;
        context.lineWidth = w / 100;
        context.lineCap = "round";
  
        // Cube parameters
        var cube_x = 0;
        var cube_y = 0;
        var cube_z = 250;
  
        var cube_size = 100;
        var cube_vertices = [
  
            // Back 4 vertices
            new POINT_3D(
                cube_x - cube_size,
                cube_y - cube_size,
                cube_z - cube_size
            ),
            new POINT_3D(
                cube_x + cube_size,
                cube_y - cube_size,
                cube_z - cube_size
            ),
            new POINT_3D(
                cube_x + cube_size,
                cube_y + cube_size,
                cube_z - cube_size
            ),
            new POINT_3D(
                cube_x - cube_size,
                cube_y + cube_size,
                cube_z - cube_size
            ),
  
            // Front 4 vertices
            new POINT_3D(
                cube_x - cube_size,
                cube_y - cube_size,
                cube_z + cube_size
            ),
            new POINT_3D(
                cube_x + cube_size,
                cube_y - cube_size,
                cube_z + cube_size
            ),
            new POINT_3D(
                cube_x + cube_size,
                cube_y + cube_size,
                cube_z + cube_size
            ),
            new POINT_3D(
                cube_x - cube_size,
                cube_y + cube_size,
                cube_z + cube_size
            ),
        ];
  
        var cube_edges = [
            [0, 1],
            [1, 2],
            [2, 3],
            [3, 0], // Back face
            [4, 5],
            [5, 6],
            [6, 7],
            [7, 4], // Front face
            [0, 4],
            [1, 5],
            [2, 6],
            [3, 7], // Connecting sides
        ];
  
        function project(points3d, w, h) {
  
            // Creating 2d point for every 3d point
            var points2d = new Array(points3d.length);
  
            var focal_length = 200;
  
            for (let index = points3d.length - 1; 
                            index > -1; --index) {
                let p = points3d[index];
  
                let x = p.x * (focal_length / p.z) + w * 0.5;
                let y = p.y * (focal_length / p.z) + h * 0.5;
  
                points2d[index] = new POINT_2D(x, y);
            }
  
            return points2d;
        }
  
        // Set up the animation loop
        var timeDifference,
            timeLast = 0;
        requestAnimationFrame(loop);
  
        function loop(currentTime) {
            timeDifference = currentTime - timeLast;
            timeLast = currentTime;
  
            // Background
            context.fillRect(0, 0, w, h);
  
            // Draw each edge
            var vertices = project(cube_vertices, w, h);
            for (let edge of cube_edges) {
                context.beginPath();
                context.moveTo(
                    vertices[edge[0]].x, 
                    vertices[edge[0]].y
                );
                  
                context.lineTo(
                    vertices[edge[1]].x, 
                    vertices[edge[1]].y
                );
                  
                context.stroke();
            }
  
            // Call the next frame
            requestAnimationFrame(loop);
        }
    </script>
</body>
  
</html>


Output:



Similar Reads

How to change the font of HTML5 Canvas using a button in Angular.js?
In this article, we are going to learn about how to change the font of HTML5 Canvas using a button in AngularJS. With the help of a click font's property can change by the user whether it is font-size or font-style. Syntax: For font size (Change the font size accordingly): variable.fontSize = "100px" For font style (Change the font style accordingl
2 min read
How to Draw Graphics using Canvas in HTML5 ?
In this article, we will draw graphics by using the canvas element in the document. This tag in HTML is used to draw graphics on a web page using JavaScript. It can be used to draw paths, boxes, texts, gradient, and adding images. By default, it does not contain borders and text. Note: This tag is new in HTML5. Syntax: &lt;canvas id = "script"&gt;
1 min read
How to sharpen blurry text in HTML5 canvas?
For getting a solution to this problem, let us first understand the problem that Why do this problem take place. The answer to this Question is the Pixels of the screen. The amount of blur often depends on the browser or the device you are using to view the Canvas. The Pixel ratios vary for different devices and so we get to see blurry effects. Sol
2 min read
How to use the canvas drawImage() method in HTML5 ?
The canvas drawImage() method of the Canvas 2D API is used to draw an image in various ways on a canvas element. This method has additional parameters that can be used to display the image or a part of the image. Syntax: context.drawImage(img, x, y, swidth, sheight, sx, sy, width, height); Approach: Add an image using the &lt;img&gt; tag.Draw the c
2 min read
How to clear the canvas for redrawing in HTML5 ?
The HTML5 canvas element is a powerful tool for drawing graphics, animations, and games in the web browser. However, when we want to update or redraw an existing drawing on the canvas, we need to first clear the canvas so that the new drawing does not overlap with the old one. In this article, we will explore two different ways to clear the canvas
4 min read
How to Set the height and width of the Canvas in HTML5?
The canvas element is a part of HTML5 which allows us for dynamic, scriptable rendering of 2D shapes and bitmap images, facilitating the creation of games, graphs, animations, and compositions. To set the height and width of the canvas in HTML5, we can utilize the height and width attributes within the &lt;canvas&gt; tag, specifying pixel values to
2 min read
How to create animation of color changing and moving cube using p5.js ?
In this article, we are going to see how to create the animation of color-changing and rotating cubes using p5.js. p5.js is a JavaScript library that helps in creating graphics that users can interact with and is easy to use and helps in visualizing different kinds of graphics and animations. This article will show you how to create the animation o
4 min read
How to create a simple editable canvas textbox using Fabric.js?
In this article, we are going to create a canvas textbox using Fabric.js. The canvas means text written in the Textbox is movable and can be stretched according to requirement. Further, the text itself can be edited into anything else too because it is a textbox. Creating structure: To make this possible we are going to use a JavaScript library cal
2 min read
How to create a canvas circle using Fabric.js ?
In this article, we are going to see how to create a canvas circle using FabricJS. The canvas means the circle is movable and can be stretched according to requirement. Further, the circle can be customized when it comes to initial stroke color, fill color, stroke width, or radius. Approach: To make it possible we are going to use a JavaScript libr
2 min read
How to create a canvas ellipse using Fabric.js ?
In this article, we are going to see how to create a canvas ellipse using FabricJS. The canvas means the ellipse is movable and can be stretched according to requirements. Further, the ellipse can be customized when it comes to initial stroke color, fill color, stroke width, or radius. Approach: To make it possible we are going to use a JavaScript
2 min read
Article Tags :
three90RightbarBannerImg