【问题标题】:Canvas Element - Rotation画布元素 - 旋转
【发布时间】:2015-11-16 07:01:03
【问题描述】:

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

有人知道我该怎么做吗?

菲尔克斯

【问题讨论】:

  • 我不清楚。您是要旋转画布上的单个元素,还是旋转包含所有元素的整个画布,还是要同时旋转单个元素和整个画布?

标签: javascript html canvas rotation multiplayer


【解决方案1】:

你可以使用CanvasRenderingContext2D.rotate()和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

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多