简体   繁体   English

绘制到 canvas 时如何缩放文本?

[英]How to scale text when drawing to canvas?

I am scaling text using CSS transform scale eg我正在使用 CSS 变换比例缩放文本,例如

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

I also need to draw the same text on a canvas element我还需要在 canvas 元素上绘制相同的文本

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

How should I scale the text in the above js function?我应该如何缩放上面的js function中的文本? I've hardcoded the font size 20px but how would I use the scale values of 2 and 4 ?我已经硬编码了字体大小20px但我将如何使用24的比例值?

You can set the context of the canvas to have scaling by calling the context's scale function.您可以通过调用上下文的比例 function 来设置 canvas 的上下文以进行缩放。

Here's an example:这是一个例子:

 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>

Don't forget to reset the scale when you've finished drawing the text.完成绘制文本后,不要忘记重置比例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM