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

リンクをくれたdr.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();

説明:

  • ctx.save()座標系の現在の状態を保存します。

  • ctx.translate(cx, cy)原点をキャンバスの中心に変更します

  • ctx.rotate(deg * Math.PI/180)正方形を45度に回転します(パラメーターは度ではなくラジアンであることに注意してください)

  • ctx.fillRect( x, y, w, h )正方形を描きます

  • ctx.restore()座標系の最後の状態を復元します。

JSフィドルリンク

HTML5スライダーを備えた別のJSフィドルリンク

于 2012-01-21T10:18:52.953 に答える
0

私が正しく覚えていれば、関連する平行移動は、最初に長方形の中心点に平行移動し、次に必要な量を回転させてから描画するようなものでした。または、おそらく最初に回転してから翻訳します。私は少し錆びています=)

于 2012-01-20T07:09:18.757 に答える
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

それに対処したくない場合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 に答える