Home > Mobile >  How to fit multiple rotating rectangle inside the canvas (Javascript)
How to fit multiple rotating rectangle inside the canvas (Javascript)

Time:10-02

as mentioned I am trying to fit a whole circle of rectangle inside a canvas, but as seen, I can only show a fourth of the circle. I made a basic html document with a canvas element. Relative to the size of the canvas element I made a single rectangel and centered it in the middle of the canvas. With that, I tried to make a for loop which should rotate the rectangle while making a full circle. But it didn't work.

body{
    background-color: #000000;
}

canvas {
    padding: 0;
    margin: auto;
    display: block;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    border:1px solid
}
<html>
    <body>
        <link rel="stylesheet" href="canvas.css">
        <canvas id="myCanvas" width="900" height="900" ></canvas>
        
        <script>
        // Get id from canvas element
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        
        // Change size of rectangle
        var recWidth = 40
        var recHeight = 40
        
        // Position rectangle in the middle of the canvas    
        var xPos = (document.getElementById("myCanvas").width/2) - (recWidth/2);   
        var yPos = (document.getElementById("myCanvas").height/2) - (recHeight/2);
        

        // Convert degree to radian
        const degToRad = (degrees) => {
            return degrees / 180 * Math.PI;
        }    
        
        // Number of rectangles
        const num = 36;

        for (let i = 0; i<num; i  ){
            const slice = degToRad (360 / num);
            const angle = slice * i; 

        context.fillStyle = 'green';
        context.save();
        context.rotate (angle);            
        context.beginPath();
        context.rect(xPos,yPos,recWidth,recHeight);
        context.fill();
        context.restore();
        }

        </script> 
        
        </body>

</html>

CodePudding user response:

The problem is that most of your squares are being drawn outside the boundaries of the canvas.

It appears the canvas rotates around (0, 0) rather than around the center.

Outside the loop:

// Use a different center and a smaller radius
var xPos = (document.getElementById("myCanvas").width/4) - (recWidth/4);   
var yPos = (document.getElementById("myCanvas").height/4) - (recHeight/4);
// Move the center 
context.translate(xPos * 2, yPos * 9/4);
context.font = "14pt Arial";

Inside the loop:

context.fill(); // existing line of code
context.fillText(i, xPos-30, yPos-30); // added
context.restore(); // existing

Also: instead of context.beginPath(), context.rect() and context.fill() you can use context.fillRect().

  • Related