javascript - 旋转 HTML 画布文本
问题描述
我有一个矩形,其边缘标记为 150
如何旋转文本“150”以从下到上阅读。下面的代码使 150 沿边缘从上到下看。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
const x = 150;
const y = 150;
const w = 200;
const h = 150;
ctx.fillStyle = "gray";
ctx.fillRect(x + 0.5, y + 0.5, w, h);
ctx.font = "12px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("Rectangle", x + w / 2, y + h / 2);
ctx.fillText('200', x + w / 2, y + h - 5);
ctx.save();
ctx.translate(x + w, y + h / 2);
ctx.rotate(90 * Math.PI / 180);
ctx.fillText('150', 0, 0 + w - 5);
ctx.restore();
<canvas id="myCanvas" width="400" height="300"></canvas>
解决方案
注意负平移和负旋转。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
const x = 150;
const y = 150;
const w = 200;
const h = 150;
ctx.fillStyle = "gray";
ctx.fillRect(x + 0.5, y + 0.5, w, h);
ctx.font = "12px Comic Sans MS";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("Rectangle", x + w / 2, y + h / 2);
ctx.fillText('200', x + w / 2, y + h - 5);
ctx.save();
ctx.translate(x - w, y + h / 2);
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText('150', 0, w + 15); /* 15 is width of the text itself */
ctx.restore();
<canvas id="myCanvas" width="400" height="300"></canvas>
推荐阅读
- php - 在 Wordpress 中按 ID 隐藏帖子和类别中的内容
- sql - 如何在 MS-Access 中按聚合函数排序?
- discord - 如何在 discord.py 中创建归档命令?
- java - 单例模式 | 代码中 volatile 的用途是什么,因为 synchronized 关键字还根据 java 内存模型提供可见性被授予者
- web-scraping - 我如何从 barchart.com 抓取这些股票代码?
- openssl - 用于在 openssl 中签名算法的自定义 OID
- aws-lambda - 模拟 Lambda.invoke 包装但未被调用
- java - 令牌“sList”上的语法错误,此令牌后应为 VariableDeclaratorId ....?如何解决这个问题..?
- ios - SFSafariViewController 智能横幅
- java - app:passwordToggleEnabled="true" 不起作用