如何更改画布文本的字体大小

我的加载屏幕上有画布上的文本,但它太小了。我以某种方式找不到任何关于更改它的正确语法的资源。


我试过:


// examples of what i've tried


canvasContext.font(40); 

canvasContext.font(40 + 'px'); 

canvasContext.fontSize(40); 

canvasContext.fontSize(40 + 'px'); 

canvasContext.font = 40; 

canvasContext.font = 40 + 'px'; 

canvasContext.fontSize = 40; 

canvasContext.fontSize = 40 + 'px';

——


//my actual code


window.onload = function () {

    canvas = document.getElementById('gameCanvas');

    canvasContext = canvas.getContext('2d');

}


function colorText(showWords, textX, textY, fillColor, fontSize) {


    //this works -----

    canvasContext.fillStyle = fillColor;

    canvasContext.fillText(showWords, textX, textY);


    //this doesn't ------

    canvasContext.fontSize = 40 + 'px';

}


富国沪深
浏览 430回答 1
1回答

慕哥6287543

你应该改变这一行:canvasContext.font= 40 + 'px';为了这:canvasContext.font = `40px Verdana`;笔记:不要忘记属性canvasContext.font应该设置在canvasContext.fillText! 但为什么?因为在fillText函数中,文本是在画布上绘制的。如果字体属性设置在之后,则画布上的文本不会改变,只有再次绘制时才会改变。遵循一个完整的工作示例://my actual codevar canvasContext;window.onload = function () {&nbsp; &nbsp; canvas = document.getElementById('gameCanvas');&nbsp; &nbsp; canvasContext = canvas.getContext('2d');&nbsp;&nbsp;&nbsp; &nbsp; colorText("Word", 30, 30, "white", "40px");}function colorText(showWords, textX, textY, fillColor, fontSize) {&nbsp; &nbsp; canvasContext.font = `${fontSize} Verdana`;&nbsp; &nbsp; canvasContext.fillStyle = fillColor;&nbsp; &nbsp; canvasContext.fillText(showWords, textX, textY);&nbsp; &nbsp;}canvas {&nbsp; background-color: blue;}<canvas id="gameCanvas"></canvas>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript