Search code examples
javascripthtmlcanvasrotationmultiplayer

Canvas Element - Rotation


I've multiple canvas elements, each one work on his own. I would like to use these to create a multiplayer. It works perfectly, but now I would like to rotate single canvas elements (180 degree). I tried the getContext('2d') method but it only helps me for a single obeject on the canvas. But what I would like to do is to rotate the WHOLE canvas.

Does someone know how I can do this?

Feilx


Solution

  • You could utilize CanvasRenderingContext2D.rotate() and CanvasRenderingContext2D.translate methods for that purpose, the following example illustrates it:

    var canvas = document.getElementById("canvas");
    var angleInput = document.getElementById("angleInput");
    canvas.width = 800;
    canvas.height = 600;
    var ctx = canvas.getContext("2d");
    
    var angleInDegrees=0;
    drawRotated(ctx,angleInDegrees);
    
    document.getElementById("clockwiseButton").addEventListener('click',function(){
    	angleInDegrees+=parseInt(angleInput.value);
    	drawRotated(ctx,angleInDegrees);
    });
    
    document.getElementById("counterclockwiseButton").addEventListener('click',function(){
    	angleInDegrees-=parseInt(angleInput.value);
    	drawRotated(ctx,angleInDegrees);
    });
    
    
    
    function drawRotated(ctx,degrees){
    	var canvasWidth = ctx.canvas.width;
        var canvasHeight = ctx.canvas.height;
        ctx.clearRect(0,0,canvasWidth,canvasHeight); // Clear the canvas
        ctx.save();
        ctx.translate(canvasWidth/2,canvasHeight/2); // Move registration point to the center of the canvas
        ctx.rotate(degrees*Math.PI/180); // Rotate
        drawObjects(ctx);
        ctx.restore();
    }
    
    
    
    function drawObjects(ctx)
    {
       //draw triangle
       ctx.beginPath();
       ctx.moveTo(200,150);
       ctx.lineTo(150,200);
       ctx.lineTo(250,200);
       ctx.fill();
    
       //draw circle
       ctx.beginPath();
       ctx.arc(350,75,50,0,Math.PI*2,false); 
       ctx.fill();
       ctx.stroke();
    
       //draw rectangle
       ctx.fillRect(50,50,150,50);
    }
    <div>
       <button id="clockwiseButton">Rotate right</button>
       <button id="counterclockwiseButton">Rotate left</button>
       <input id="angleInput" value="45"></input>
    </div>
    <canvas id="canvas"></canvas>

    JSFiddle