點燈坊

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

Canvas Overview

Sam Xiao's Avatar 2022-10-17

We can use Canvas to draw images without any packages.

Version

HTML 5

Canvas

overview000

Use HTML 5 Canvas to draw a rectangle.

<!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.strokeStyle = 'red'
    context.lineWidth = 2
    context.strokeRect(20, 50, 100, 100)
  </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.strokeStyle = 'red'
context.lineWidth = 2
context.strokeRect(20, 50, 100, 100)
  • Use strokeStyle to set the border color of the rectangle
  • Use lineWidth to set the border width
  • Use strokeRect() to draw a rectangle

Conclusion

  • We don’t have to use any packages to use Canvas API to draw the image