Skip to content

图片裁剪

作者:Yuan Tang
更新于:5 个月前
字数统计:181 字
阅读时长:1 分钟

获取图片

先获取用户选择上传的图片:

vue
<script setup>
import { ref } from 'vue'

const imgUrl = ref('')
const canvasRef = ref(null)
const imgRef = ref(null)
function onChangeFn(e) {
  // 获取用户上传的文件
  const file = e.target.files[0]

  // 预览文件
  const fr = new FileReader()
  fr.readAsDataURL(file)

  // 获取图片读完的图片结果(非同步,需要在onload获取)
  fr.onload = () => {
    imgUrl.value = fr.result
  }
}
</script>

<template>
  <input type="file" @change="onChangeFn">
  <img ref="imgRef" :src="imgUrl">
  <canvas ref="canvasRef" height="200" width="200" />
</template>

裁剪图片

裁剪图片使用 drawImage() 方法,通过后几位的参数实现裁剪后替换。代码如下所示:

js
// ...
fr.onload = () => {
  imgUrl.value = fr.result

  const ctx = canvasRef.value.getContext('2d')

  // 等比计算截取的图片宽高
  const height = (200 / imgRef.value.height) * imgRef.value.naturalHeight
  const width = (200 / imgRef.value.width) * imgRef.value.naturalWidth

  ctx.drawImage(imgRef.value, 0, 0, width, height, 0, 0, 200, 200)
}

Contributors

Yuan Tang