create a rotating 3d cube in javascript

To create a rotating 3D cube in JavaScript, we will need to use a combination of HTML5 canvas, matrix transformations, and requestAnimationFrame() method. Here's an example code for creating a cube that rotates on its Y-axis:

<canvas id="myCanvas"></canvas>

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

    let angle = 0;
    
    function drawCube() {
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const size = 100;
          
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.save();
          
        context.translate(centerX, centerY);
        context.rotate(angle);
          
        context.fillStyle = 'red';
        context.fillRect(-size / 2, -size / 2, size, size);
          
        context.fillStyle = 'blue';
        context.fillRect(-size / 2, -size / 2, size, size);
          
        context.strokeStyle = 'black';
        context.strokeRect(-size / 2, -size / 2, size, size);
          
        context.restore();
          
        angle += Math.PI / 180;
        requestAnimationFrame(drawCube);
    }
      
    drawCube();
</script>
975 chars
37 lines

In this code, we are using the canvas element to draw a square and rotate it around its Y-axis. We are first setting up the canvas context and defining the center point of the square to be drawn. Then, we clear the complete screen by calling context.clearRect().

We then use the context.save() method to save the current state of the context and apply the required transformations, in this case, rotation around the Y-axis. We then define a few fill styles for the cube's faces and draw the 6 sides of the cube in the required positions. Finally, we restore the context to its previously saved state, increasing the angle by a small amount to get the animation effect, and render the next frame using requestAnimationFrame().

gistlibby LogSnag