點燈坊

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

使用 Canvas 同時繪製圖片與矩形

Sam Xiao's Avatar 2020-11-24

若要同時顯示圖片與矩形,也可使用 HTML 5 Canvas 繪製圖片與矩形。

Version

Vue 2.6.11
HTML 5

Canvas

canvas000

HTML 5 Canvas 除了繪製圖片外,同時繪製了矩形將臉部框起來。

<template>
  <canvas ref="canvas"/>
</template>

<script>
let mounted = function() {
  let context = this.$refs.canvas.getContext('2d')
  context.canvas.width = innerWidth
  context.canvas.height = innerHeight

  let image = new Image
  image.src = 'https://konvajs.org/assets/yoda.jpg'
  image.onload = () => {
    context.drawImage(image, 5, 5)
    context.strokeStyle = 'red'
    context.lineWidth = 2
    context.strokeRect(40, 15, 120, 135)
  }
}

export default {
  name: 'App',
  mounted
}
</script>

第 2 行

<canvas ref="canvas"/>

使用 HTML 5 的 <canvas> tag,為了能讓 Vue 控制,特別加上 ref

第 7 行

let context = this.$refs.canvas.getContext('2d')
context.canvas.width = innerWidth
context.canvas.height = innerHeight
  • 使用 $refs 取得 canvas ref,並指使用其 2d context
  • 設定 canvas 的長寬

11 行

let image = new Image
image.src = 'https://konvajs.org/assets/yoda.jpg'
image.onload = () => {
  context.drawImage(image, 5, 5)
  context.strokeStyle = 'red'
  context.lineWidth = 2
  context.strokeRect(40, 15, 120, 135)
}

drawImage()strokeRect() 都寫在 onload event 內。

Conclusion

  • 若想完全以 code 繪製 HTML 5 Canvas,其實可不必使用 package,直接使用 Canvas API 即可