Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - Cannot set canvas width and change font at the same time?

http://jsfiddle.net/sLk72mud/

Inn the jsfiddle, the call to measureText that sets the canvas width:

tCtx.canvas.width = tCtx.measureText(this.value).width;

overwrites the font size:

tCtx.font = "25px serif"

If I remove the call to measureText, then the canvas uses the font size I expect. Unfortunately I then have to guess on how wide to make my canvas. Why is this and is there a better way to do it?

question from:https://stackoverflow.com/questions/65602038/cannot-set-canvas-width-and-change-font-at-the-same-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Changing the canvas dimensions also resets the context. You'll need to set the font again (and any other non-default settings) after the resize.

   tCtx.font = 'bold 24px serif';
   tCtx.canvas.width = tCtx.measureText(this.value).width;
   tCtx.font = 'bold 24px serif';
   tCtx.fillText(this.value, 0, 10);

Saved states (via .save()/.restore()) are also lost on a resize. If you expect to have a number of changes to the canvas state, you may want to break these out into your own .save()/.restore() functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...