Set the canvas size using CSS or the HTML width/height attributes to be, for example, 200 x 400:
使用CSS或HTML width / height属性将画布大小设置为例如200 x 400:
<canvas width="200" height="400"></canvas>
and make sure you also set the width/height properties of the canvas object in the JavaScript, to avoid the text to render blurry, for example:
并确保还设置JavaScript中canvas对象的width / height属性,以避免文本呈现模糊,例如:
canvas.width = 1800
canvas.height = 1200
First thing, get a reference to a canvas
首先,获取对画布的引用
const canvas = document.querySelector('canvas')
and create a context object from it:
并从中创建一个上下文对象:
const context = canvas.getContext('2d')
Now we can call the fillText()
method of the context object:
现在我们可以调用上下文对象的fillText()
方法:
context.fillText('hi!', 100, 100)
Make sure the x and y coordinates of the starting point are included in the canvas size.
确保起点的x和y坐标包含在画布尺寸中。
You can pass additional properties before calling fillText()
to customize the appearance, for example:
您可以在调用fillText()
来自定义外观之前传递其他属性,例如:
context.font = 'bold 70pt Menlo'
context.fillStyle = '#ccc'
context.fillText('hi!', 100, 100)