3

我想创建一个在其轴上旋转正方形的函数。

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);

功能:

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

这个怎么做?

4

4 回答 4

6

Thanks dr.dredel for the link.

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.translate(cx, cy) changes the origin to the center of canvas

  • ctx.rotate(deg * Math.PI/180) rotates the square to 45 degrees (Note that the parameter is in radians, not degrees)

  • ctx.fillRect( x, y, w, h ) draws the square

  • ctx.restore() restores the last state of the coordinate system.

JS Fiddle link.

Another JS Fiddle link, with a HTML5 slider.

于 2012-01-21T10:18:52.953 回答
0

这是我的意见:

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 是旧位置,ctx 是形状的新位置。您必须根据要放置形状的位置来平移具有相同 x,y 坐标的形状。然后您必须输入值以ctx.fillRect(x,y,w,h);将 x 和 y 保持为 -ve 值(高度和宽度的一半以将其保持在画布的对角线上,否则更改以操纵它)。和 h, w 作为您想要的值。

DMEO

于 2014-03-17T12:36:57.727 回答
0

如果我没记错的话,所涉及的平移类似于首先平移到矩形的中心点,然后旋转所需的量,然后绘制。或者可能先旋转,然后翻译,我有点生疏=)

于 2012-01-20T07:09:18.757 回答
0

如果您不想处理ctx.save()所有这些,有一种简单的方法可以计算旋转正方形的每个新点应该在哪里。

下面会画一个绿色方块,然后再画一个旋转了22.5°的红色方块。

const ctx = document.querySelector("canvas").getContext("2d");

ctx.fillStyle = "green";
ctx.fillRect(50, 50, 50, 50)

/**
 * 
 * @returns {[number, number]} (x3, y3)
 */
function f(x1, y1, x2, y2, degrees) {
    const rad = degrees * Math.PI / 180;
    return [
        (x2 - x1) * Math.cos(rad) + x1 - (y2 - y1) * Math.sin(rad),
        (x2 - x1) * Math.sin(rad) + y1 + (y2 - y1) * Math.cos(rad)
    ]
}

ctx.fillStyle = "red";
const centre = 75;
/*
 * The centre of the square is at (75, 75)
 * The corner points are at:
 * (50, 50)
 * (100, 50)
 * (100, 100)
 * (50, 100)
 */

ctx.beginPath();
let [newX, newY] = f(centre, centre, 50, 50, 22.5);
ctx.moveTo(newX, newY);

[newX, newY] = f(centre, centre, 100, 50, 22.5);
ctx.lineTo(newX, newY);

[newX, newY] = f(centre, centre, 100, 100, 22.5);
ctx.lineTo(newX, newY);

[newX, newY] = f(centre, centre, 50, 100, 22.5);
ctx.lineTo(newX, newY);

[newX, newY] = f(centre, centre, 50, 50, 22.5);
ctx.lineTo(newX, newY);

ctx.fill();
<canvas width=200 height=200 style="background:gray"></canvas>

我把这张图放在一起认为它可能有助于可视化正在发生的事情。

旋转正方形的示例

于 2022-02-08T23:32:22.030 回答