這裏fillText直接使用rotate會有問題。估計是旋轉中心有問題。
正確的邏輯爲:
先使用translate移動中心點在文本起始位置,如何在0,0處fillText即可。
如果要在字符串中心進行旋轉,則需要獲取字符串長度,translate的時候x進行+,y軸進行-即可。
程序運行截圖如下:
綠色的爲原始字符串,紅色是從頂部進行旋轉,綠色爲在中心進行旋轉。
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
當前瀏覽器不支持canvas
</canvas>
<script>
window.onload = function(){
let canvas = document.getElementById("canvas");
canvas.width = 1980;
canvas.height = 1024;
let context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillText("中文ABCDEFG", 400, 400);
context.save();
context.translate(400, 400);
context.rotate(90 * Math.PI / 180);
context.fillStyle = "red";
context.fillText("中文ABCDEFG", 0, 0);
context.restore();
//中心位置旋轉
let strWidth = context.measureText("中文ABCDEFG").width;
console.log("strWidth:" + strWidth);
context.save();
context.translate(400 + strWidth / 2, 400 - strWidth / 2);
context.rotate(90 * Math.PI / 180);
context.fillStyle = "blue";
context.fillText("中文ABCDEFG", 0, 0);
context.restore();
}
</script>
</body>
</html>