JavaScript 旋转

摘要:在本教程中,您将学习如何使用 JavaScript rotate() 方法来旋转绘图对象。

JavaScript rotate() canvas API 简介

rotate() 是 2D 绘图上下文的 method。rotate() method 允许您在画布上旋转绘图对象。

以下是 rotate() method 的语法

ctx.rotate(angle)Code language: CSS (css)

rotate() method 接受以弧度为单位的旋转角度。

如果角度为正,则旋转方向为顺时针。如果角度为负,则旋转方向为逆时针。

要将度数转换为弧度,可以使用以下公式

degree * Math.PI / 180Code language: JavaScript (javascript)

添加旋转时,rotate() method 使用画布原点作为旋转中心点。

下图说明了旋转

如果要更改旋转中心点,需要使用 translate() method 移动画布原点。

JavaScript rotate() 示例

以下示例 从画布中心开始绘制一个红色矩形。然后将画布原点移动到画布中心,并以 45 度角绘制第二个矩形

HTML

<canvas id="canvas" height="300" width="500">
</canvas>Code language: HTML, XML (xml)

JavaScript

const canvas = document.querySelector('#canvas');

if (canvas.getContext) {

    // rectangle's width and height
    const width = 150,
        height = 20;

    // canvas center X and Y
    const centerX = canvas.width / 2,
        centerY = canvas.height / 2;

    const ctx = canvas.getContext('2d');

    // a red rectangle
    ctx.fillStyle = 'red';
    ctx.fillRect(centerX, centerY, width, height);

    // move the origin to the canvas' center
    ctx.translate(centerX, centerY);

    // add 45 degrees rotation
    ctx.rotate(45 * Math.PI / 180);

    // draw the second rectangle
    ctx.fillStyle = 'rgba(0,0,255,0.5)';
    ctx.fillRect(0, 0, width, height);

}Code language: JavaScript (javascript)

以下是演示链接。

输出

摘要

  • 使用 JavaScript rotate() method 在画布上旋转绘图对象。
本教程对您有帮助吗?