0

Using the package node-canvas, I need to render a username - one that can be rather large. I need to ensure that the text can dynamically scale the size of it to fit into a pre-defined image, so that the name is never cut off, it just gets smaller so more characters can be rendered. I have considered using jimp and sharp, but couldn't find the optimal outcome.

Thanks.

2 Answers2

0

This is how you can display text in Javascript inside a canvas:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50); 

You can set the font as:

ctx.font = "30px Arial";

This is all you need from a strickly technical point of view. However, since you have a size constraint, you will need to adhere to some boundary limits. To see what fits into what sizes, you can use measureText. You can get the canvas dimensions as well, using the width and height properties. So, if you are to implement this yourself, you will have to experiment with boundaries, sizes and fonts until you are satisfied with the results.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

There are different types of units in HTML / CSS, which can be absolute, or relative. CSS EM, PX, PT, CM, IN…

Ex, if you use "10px" as a default font height, it will look the same on any screen size, but if you use "10vw", the height will change with the width of the window.

You can also use "%" for the same effect, which usually relates to the size of the parent element.

But the best option is to create an event function that changes the width of the font based on the canvas size so that the font never gets too big or too small.

Canilho
  • 944
  • 5
  • 11