Skip to content

canvas 图像和视频

canvas 的 API 可以获取以下类型的资源绘制图像或视频。

  • HTMLImageElement。这些图片是由 Image() 函数构造出来的,或者任何的 img 元素。
  • HTMLVideoElement。用一个 HTML 的 video 元素作为你的图片源,可以从视频中抓取当前帧作为一个图像。
  • HTMLCanvasElement。可以使用另一个 canvas 元素作为你的图片源。
  • ImageBitmap。这是一个高性能的位图,可以低延迟地绘制,它可以从上述的所有源以及其它几种源中生成。

绘制一张线上链接的图片

关键 api:

js
// 参数:绘制源,图片左上角的 x 坐标,图片左上角对的 y 坐标。
ctx.drawImage(img, 0, 0)

drawImage 还有重载方法。

所有代码:
vue
<template>
  <canvas id="online-image" width="100" height="100"></canvas>
</template>
<script setup lang='ts'>
import { onMounted } from 'vue';
onMounted(() => {
  const oic = document.getElementById('online-image') as HTMLCanvasElement
  const ctx = oic.getContext('2d')!
  ctx.strokeRect(0, 0, 100, 100)
  const img = new Image()
  img.src = 'https://certification.vuejs.org/images/vue-badge.svg'
  img.onload = () => {
    // 参数:绘制源,图片宽,图片高
    ctx.drawImage(img, 0, 0)
  }
})
</script>

缩放 scaling

上个例子我们使用了 drawImage(img, x, y) 来绘制图片。我们还可以使用重载方法 drawImage(img, x, y, width, height) 来控制图片的宽高,也就是缩放图片。

只需要将上个例子的代码稍微改动一下:

vue
<template>
  <canvas id="online-image-scale" width="200" height="200"></canvas>
</template>
<script setup lang='ts'>
import { onMounted } from 'vue';
onMounted(() => {
  const oic = document.getElementById('online-image-scale') as HTMLCanvasElement
  const ctx = oic.getContext('2d')!
  ctx.strokeRect(0, 0, 200, 200)
  const img = new Image()
  img.src = 'https://certification.vuejs.org/images/vue-badge.svg'
  img.onload = () => {
    // 参数:绘制源,图片宽,图片高
    ctx.drawImage(img, 0, 0, 200, 200) 
  }
})
</script>

切片

drawImage 还有最后一个重载方法,drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

第一个参数是图像源。后面的前 4 个参数定义切片的位置和大小。后 4 个参数定义切片显示在 canvas 中的位置。

下面举一个例子,只显示 vue logo 的右半边。

代码:
vue
<template>
  <canvas id="online-image-slice" width="200" height="200"></canvas>
</template>
<script setup lang='ts'>
import { onMounted } from 'vue';
onMounted(() => {
  const oic = document.getElementById('online-image-slice') as HTMLCanvasElement
  const ctx = oic.getContext('2d')!
  ctx.strokeRect(0, 0, 200, 200)
  const img = new Image()
  img.src = 'https://certification.vuejs.org/images/vue-badge.svg'
  img.onload = () => {
    const imgWidth = img.width
    const imgHeight = img.height
    ctx.drawImage(img, imgWidth / 2, 0, imgWidth / 2, imgHeight, 100, 0, 100, 200) 
  }
})
</script>

控制缩放行为

过度缩放图像可能会导致图像模糊或像素化。您可以通过使用绘图环境的 imageSmoothingEnabled 属性来控制是否在缩放图像时使用平滑算法。默认值为 true,即启用平滑缩放。您也可以像这样禁用此功能:

js
ctx.mozImageSmoothingEnabled = false
ctx.webkitImageSmoothingEnabled = false
ctx.msImageSmoothingEnabled = false
ctx.imageSmoothingEnabled = false

Released under the MIT License.