點燈坊

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

Using Canvas to Scale Image

Sam Xiao's Avatar 2022-10-17

We can also use Canvas to scale the image.

Version

HTML 5

Canvas

scale000

The picture is scaled by Canvas, not by <img>.

<!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

    let image = new Image()
    image.src = 'https://konvajs.org/assets/yoda.jpg'

    let scale = 0.5
    let width = image.width * scale
    let height = image.height * scale
    image.onload = () => context.drawImage(image, 5, 5, width, height)
  </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 16

let image = new Image()
image.src = 'https://konvajs.org/assets/yoda.jpg'
  • Create an image on the fly

Line 19

let scale = 0.5
let width = image.width * scale
let height = image.height * scale
image.onload = () => context.drawImage(image, 5, 5, width, height)
  • Scale the image to 50%
  • When the image is created, the load event is fired. Use context‘s drawImage() to draw an image by Canvas on load event

Conclusion

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