在画布上绘制时如何缩放文本



我正在使用CSS转换比例缩放文本,例如

transform: scale(2, 4);
fontSize: 20px // do I need to include fontSize?

我还需要在画布元素上绘制相同的文本

function draw() {
const ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '20px serif';
ctx.fillText('Hello world', 10, 50);
}

我应该如何缩放上面js函数中的文本?我已经对字体大小20px进行了硬编码,但如何使用24的比例值?

您可以通过调用上下文的scale函数来将画布的上下文设置为具有缩放功能。

这里有一个例子:

function draw() {
const ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '20px serif';
ctx.scale(2, 4);
ctx.fillText('Hello world', 10, 50);
}
window.onload = draw;
<canvas id="canvas" width="250" height="250"></canvas>

绘制完文本后,不要忘记重置比例。

最新更新