點燈坊

失くすものさえない今が強くなるチャンスよ

Using Canvas to Draw Text with Shadows

Sam Xiao's Avatar 2022-10-17

We can also use Canvas to draw text with shadows.

Version

HTML 5

Canvas

shadow000

The text is drawn with shadows 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.shadowOffsetX = 2
    context.shadowOffsetY = 2
    context.shadowColor = 'rgba(0, 0, 0, 1)'
    context.shadowBlur = 1

    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 get canvas element, and getContext() to get its 2d context
  • Set Canvas’s width and height by window‘s innerWidth and innerHeight

Line 17

context.font = '15px Verdana'
context.fillStyle = 'red'
  • Use font to set font and font size
  • Use fillStyle to set font color

Line 20

context.shadowOffsetX = 2
context.shadowOffsetY = 2
context.shadowColor = 'rgba(0, 0, 0, 1)'
context.shadowBlur = 1
  • Use shadowOffsetX to set offset X coordination of the shadow
  • Use shadowOffsetY to set offset Y coordination of the shadow
  • Use shadowColor to set the shadow’s color. It is a string
  • Use shadowBlur to set the blur state. A larger number means more blur

Line 25

context.fillText('37.5', 40, 20)
  • 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