简体   繁体   English

在HTML5 Canvas中沿其轴旋转正方形吗?

[英]Rotate square on its axis in HTML5 Canvas?

I want to create a function that rotates a square on its axis. 我想创建一个在其轴上旋转正方形的函数。

var halfWidth = canvas.width/2;
var halfHeight = canvas.height/2;

var x = halfWidth-10;
var y = halfHeight-10;
var w = 20;
var h = 20;
var deg = 45;

rotate(x, y, w, h, deg);

ctx.fillRect(x, y, w, h);

The function: 功能:

function rotate(x, y, w, h, deg) {
    // ctx.translate() and ctx.rotate()
    // goes here.
}

How to do this? 这个怎么做?

Thanks dr.dredel for the link. 感谢dredel博士提供的链接。

var cx = canvas.width/2;
var cy = canvas.height/2;

var x = -10;
var y = -10;
var w = 20;
var h = 20;
var deg = 45;

ctx.save();

ctx.translate(cx, cy);
ctx.rotate(deg * Math.PI/180);

ctx.fillRect(x, y, w, h);

ctx.restore();

Explanation: 说明:

  • ctx.save() saves the current state of the coordinate system. ctx.save()保存坐标系的当前状态。

  • ctx.translate(cx, cy) changes the origin to the center of canvas ctx.translate(cx, cy)将原点更改为画布的中心

  • ctx.rotate(deg * Math.PI/180) rotates the square to 45 degrees (Note that the parameter is in radians, not degrees) ctx.rotate(deg * Math.PI/180)将正方形旋转到45度(请注意,该参数以弧度而非度为单位)

  • ctx.fillRect( x, y, w, h ) draws the square ctx.fillRect( x, y, w, h )绘制正方形

  • ctx.restore() restores the last state of the coordinate system. ctx.restore()恢复坐标系的最后状态。

JS Fiddle link . JS小提琴链接

Another JS Fiddle link, with a HTML5 slider . 另一个JS Fiddle链接,带有HTML5滑块

here is my opinion: 这是我的意见:

JAVASCRIPT JAVASCRIPT

var canvas = document.getElementById("myCanvas");
var ctx2 = canvas.getContext("2d");
ctx2.fillStyle='#333';

ctx2.fillRect(50,50,100,100);
var ctx = canvas.getContext("2d");


ctx.fillStyle='red';

var deg = Math.PI/180;

ctx.save();
    ctx.translate(100, 100);
    ctx.rotate(45 * deg);
    ctx.fillRect(-50,-50,100,100);
ctx.restore();

ctx2 is the old position and ctx is the new position of the shape. ctx2是形状的旧位置,而ctx是形状的新位置。 You have to translate the shape with the same x,y coordinates according to where you want position your shape. 您必须根据要放置形状的位置来转换具有相同x,y坐标的形状。 Then you have to enter values to ctx.fillRect(x,y,w,h); 然后,您必须将值输入ctx.fillRect(x,y,w,h); keep x and y as the -ve values (half of height and width to keep it on the diagonal to the canvas otherwise change to manipulate it). 保持x和y为-ve值(高度和宽度的一半,以使其保持在画布的对角线上,否则进行更改以对其进行操作)。 and h, w as your desired values. 和h,w作为您想要的值。

DMEO DMEO

If I remember correctly the translation involved was something like first translate to the center point of the rectangle, then rotate wanted amount, then draw. 如果我没记错的话,所涉及的平移就像是先平移到矩形的中心点,然后旋转所需的量,然后绘制。 Or possibly first rotate, then translate, I'm a bit rusty =) 或者可能先旋转然后翻译,我有点生锈=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM