Canvas 元素 - 旋转

Canvas Element - Rotation

我有多个 canvas 元素,每个元素都独立工作。我想用这些来创建多人游戏。它工作得很好,但现在我想旋转单个 canvas 元素(180 度)。我尝试了 getContext('2d') 方法,但它只对 canvas 上的单个对象有帮助。但我想做的是旋转整个 canvas.

有人知道我该怎么做吗?

Feilx

您可以为此目的使用 CanvasRenderingContext2D.rotate() and CanvasRenderingContext2D.translate 方法,以下示例对此进行了说明:

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