You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Canvas中绘制位于旋转黑矩形下方的包围红矩形(顶点触四边)

实现Canvas中旋转黑矩形的外切红矩形

要实现红色矩形位于旋转黑矩形下方,且黑矩形四个顶点分别触碰红矩形四条边的效果,核心是通过计算旋转后黑矩形的顶点极值来确定红矩形的边界,具体实现如下:

完整代码实现

HTML部分

<canvas id="myCanvas1" width="600" height="250"></canvas>

JavaScript部分

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

// 黑色矩形属性
const width = 50;
const height = 200;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const degrees = -10; // 逆时针旋转10度
const radians = (degrees * Math.PI) / 180;

// 计算旋转后黑色矩形的四个顶点坐标
// 原始矩形的四个顶点(以自身中心为原点)
const originalPoints = [
  { x: -width/2, y: -height/2 },
  { x: width/2, y: -height/2 },
  { x: width/2, y: height/2 },
  { x: -width/2, y: height/2 }
];

// 对每个顶点进行旋转变换,再平移到画布中心
const rotatedPoints = originalPoints.map(point => {
  const rotatedX = point.x * Math.cos(radians) - point.y * Math.sin(radians);
  const rotatedY = point.x * Math.sin(radians) + point.y * Math.cos(radians);
  return {
    x: rotatedX + centerX,
    y: rotatedY + centerY
  };
});

// 找出所有顶点的x、y极值,确定红矩形的边界
const minX = Math.min(...rotatedPoints.map(p => p.x));
const maxX = Math.max(...rotatedPoints.map(p => p.x));
const minY = Math.min(...rotatedPoints.map(p => p.y));
const maxY = Math.max(...rotatedPoints.map(p => p.y));

// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);

// 先绘制红色外切矩形(保证位于黑矩形下方)
ctx.fillStyle = 'red';
ctx.fillRect(minX, minY, maxX - minX, maxY - minY);

// 绘制旋转后的黑色矩形
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(radians);
ctx.fillStyle = 'black';
ctx.fillRect(-width / 2, -height / 2, width, height);
ctx.restore();

关键逻辑说明

  • 顶点计算:先定义原始矩形的四个顶点,通过旋转变换公式计算旋转后的坐标,再平移到画布中心位置,得到黑矩形实际的顶点位置。
  • 外切矩形边界:通过旋转后顶点的x、y极值,直接确定红矩形的左上角坐标、宽度和高度,确保黑矩形的四个顶点刚好触碰红矩形的四条边。
  • 绘制顺序:先绘制红矩形再绘制黑矩形,保证红矩形在视觉上位于黑矩形下方。

内容的提问来源于stack exchange,提问作者dc09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:33:31