跳到主要内容

transform

2024年06月19日
柏拉文
越努力,越幸运

一、认识


transform()Canvas 2D API 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。变换矩阵 描述如下:

--            --
| a c e |
| b d f |
| 0 0 1 |
-- --

二、语法


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

ctx.setTransform(a, b, c, d, e, f);
  • a (m11): 水平缩放

  • b (m12): 垂直倾斜。

  • c (m21): 水平倾斜。

  • d (m22): 垂直缩放。

  • e (dx): 水平移动。

  • f (dy): 垂直移动。

三、场景


3.1 绘制矩形,并以起始点为中心,平移

function drawTranslateRectangle() {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 400;
canvas.height = 400;

// 平移前 绘制矩形
ctx.fillStyle = "grey";
ctx.fillRect(0, 0, 200, 100);

// 通过 transform 平移画布
ctx.transform(1, 0, 0, 1, 100, 100);

// 平移后 绘制矩形
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 200, 100);

document.body.appendChild(canvas);
}

drawTranslateRectangle();

3.2 绘制矩形, 并以起始点为中心, 旋转 30 度

function drawRotateRectangle(params) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 400;
canvas.height = 400;

// 旋转前 绘制矩形
ctx.fillStyle = "grey";
ctx.fillRect(200, 0, 100, 50);

// 旋转画布
const degress1 = 30 * (Math.PI / 180);
const cos1 = Math.cos(degress1);
const sin1 = Math.sin(degress1);
ctx.transform(cos1, sin1, -sin1, cos1, 0, 0);

// 旋转后 绘制矩形
ctx.fillStyle = "red";
ctx.fillRect(200, 0, 100, 50);

// 旋转画布
const degress2 = 32 * (Math.PI / 180);
const cos2 = Math.cos(degress2);
const sin2 = Math.sin(degress2);
ctx.transform(cos2, sin2, -sin2, cos2, 0, 0);

// 旋转后 绘制矩形
ctx.fillStyle = "blue";
ctx.fillRect(200, 0, 100, 50);

document.body.appendChild(canvas);
}

drawRotateRectangle();

3.3 绘制文本, 并以起始点为中心, 旋转 -30 度

function drawRotateText() {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 180;
canvas.height = 100;

// 先旋转
const degress = -30 * (Math.PI / 180);
const cos = Math.cos(degress);
const sin = Math.sin(degress);
ctx.transform(cos, sin, -sin, cos, 0, 0);

// 再绘制
ctx.fillStyle = "#000";
ctx.font = `16px serif`;
ctx.fillText("旋转文案", 0, 80);

document.body.appendChild(canvas);
}

drawRotateText();