Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...