We can also use Canvas to draw text.
Version
HTML 5
Canvas
The text is drawn by Canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canvas Lab</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
let context = document.querySelector('#canvas').getContext('2d')
context.canvas.width = innerWidth
context.canvas.height = innerHeight
context.font = '15px Verdana'
context.fillStyle = 'red'
context.fillText('37.5', 40, 20)
</script>
</html>
Line 9
<canvas id="canvas"></canvas>
- Use HTML’s
<canvas>
tag to draw image - Add
id
to control the<canvas>
tag
Line 12
let context = document.querySelector('#canvas').getContext('2d')
context.canvas.width = innerWidth
context.canvas.height = innerHeight
- Use
querySelector()
to getcanvas
element, andgetContext()
to get its2d
context - Set Canvas’s width and height by
window
‘sinnerWidth
andinnerHeight
Line 17
context.font = '15px Verdana'
context.fillStyle = 'red'
context.fillText('37.5', 40, 20)
- Use
font
to set font and font size - Use
fillStyle
to set font color - Use
fillText()
to set text content and position
Conclusion
- We don’t have to use any packages to use Canvas API to draw the image