当前位置:首页 > VUE

vue项目实现截取图片

2026-02-22 04:38:10VUE

使用Canvas实现图片截取

在Vue项目中可以通过Canvas API实现图片截取功能。创建一个自定义组件,接收图片URL和截取区域参数,利用Canvas的drawImage方法进行裁剪。

<template>
  <div>
    <input type="file" @change="handleFileUpload">
    <canvas ref="canvas"></canvas>
    <button @click="cropImage">截取图片</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleFileUpload(e) {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.onload = (event) => {
        this.imageSrc = event.target.result
        this.drawOriginalImage()
      }
      reader.readAsDataURL(file)
    },
    drawOriginalImage() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      const img = new Image()
      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)
      }
      img.src = this.imageSrc
    },
    cropImage() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      const croppedCanvas = document.createElement('canvas')
      const croppedCtx = croppedCanvas.getContext('2d')

      // 设置截取区域(示例为中央200x200区域)
      const cropWidth = 200
      const cropHeight = 200
      const cropX = (canvas.width - cropWidth) / 2
      const cropY = (canvas.height - cropHeight) / 2

      croppedCanvas.width = cropWidth
      croppedCanvas.height = cropHeight
      croppedCtx.drawImage(
        canvas,
        cropX, cropY, cropWidth, cropHeight,
        0, 0, cropWidth, cropHeight
      )

      // 获取截取后的图片数据
      const croppedImage = croppedCanvas.toDataURL('image/png')
      console.log(croppedImage) // 这里可以输出或保存截取结果
    }
  }
}
</script>

使用第三方库vue-cropper

vue-cropper是一个专门用于Vue的图片裁剪组件,提供更丰富的交互功能。安装后可直接在项目中使用。

安装依赖:

npm install vue-cropper

组件实现:

<template>
  <div>
    <input type="file" @change="uploadImg">
    <vue-cropper
      ref="cropper"
      :img="imgSrc"
      :autoCrop="true"
      :fixed="true"
      :fixedNumber="[1, 1]"
    ></vue-cropper>
    <button @click="crop">截取图片</button>
  </div>
</template>

<script>
import VueCropper from 'vue-cropper'
export default {
  components: { VueCropper },
  data() {
    return {
      imgSrc: ''
    }
  },
  methods: {
    uploadImg(e) {
      const file = e.target.files[0]
      if (!/\.(jpg|jpeg|png|gif)$/.test(file.name)) {
        alert('请上传图片文件')
        return
      }
      const reader = new FileReader()
      reader.onload = (event) => {
        this.imgSrc = event.target.result
      }
      reader.readAsDataURL(file)
    },
    crop() {
      this.$refs.cropper.getCropData((data) => {
        // data为截取后的图片base64数据
        console.log(data)
      })
    }
  }
}
</script>

响应式截取区域设置

实现动态调整截取区域大小和位置的功能,可以通过监听鼠标事件来更新截取参数。

// 在Canvas方案基础上增加以下代码
data() {
  return {
    isDragging: false,
    startX: 0,
    startY: 0,
    cropX: 0,
    cropY: 0,
    cropWidth: 200,
    cropHeight: 200
  }
},
methods: {
  handleMouseDown(e) {
    const canvas = this.$refs.canvas
    const rect = canvas.getBoundingClientRect()
    this.isDragging = true
    this.startX = e.clientX - rect.left
    this.startY = e.clientY - rect.top
  },
  handleMouseMove(e) {
    if (!this.isDragging) return
    const canvas = this.$refs.canvas
    const rect = canvas.getBoundingClientRect()
    const mouseX = e.clientX - rect.left
    const mouseY = e.clientY - rect.top

    this.cropWidth = mouseX - this.startX
    this.cropHeight = mouseY - this.startY
    this.drawSelectionBox()
  },
  handleMouseUp() {
    this.isDragging = false
  },
  drawSelectionBox() {
    const canvas = this.$refs.canvas
    const ctx = canvas.getContext('2d')
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 重绘原始图片
    const img = new Image()
    img.onload = () => {
      ctx.drawImage(img, 0, 0)
      // 绘制选择框
      ctx.strokeStyle = 'red'
      ctx.lineWidth = 2
      ctx.strokeRect(
        this.startX, 
        this.startY, 
        this.cropWidth, 
        this.cropHeight
      )
    }
    img.src = this.imageSrc
  }
}

保存截取结果

将截取后的图片转换为Blob对象或Base64数据,可用于上传或下载。

vue项目实现截取图片

methods: {
  saveCroppedImage(croppedDataURL) {
    // 方法1:下载图片
    const link = document.createElement('a')
    link.href = croppedDataURL
    link.download = 'cropped-image.png'
    link.click()

    // 方法2:转换为Blob上传
    fetch(croppedDataURL)
      .then(res => res.blob())
      .then(blob => {
        const formData = new FormData()
        formData.append('image', blob, 'cropped.png')
        // 上传formData到服务器
      })
  }
}

标签: 项目图片
分享给朋友:

相关文章

vue 实现图片单选

vue 实现图片单选

Vue 实现图片单选功能 在 Vue 中实现图片单选功能,可以通过结合 v-model 和自定义事件来实现。以下是具体实现方法: 方法一:使用 v-model 和计算属性 创建一个 Vue 组件…

js实现图片的拖动

js实现图片的拖动

实现图片拖动的步骤 HTML 结构 在 HTML 中创建一个可拖动的图片元素,确保设置 draggable 属性为 true。 <img id="draggable-img" src="ima…

vue实现音乐项目

vue实现音乐项目

Vue实现音乐项目的基本步骤 使用Vue实现音乐项目通常涉及前端界面开发、音频播放控制、API数据交互等核心功能。以下是关键实现方法: 项目初始化与基础配置 创建Vue项目并安装必要依赖: vue…

vue实现图片插件

vue实现图片插件

Vue 图片插件实现方案 在 Vue 中实现图片插件通常涉及图片展示、懒加载、预览等功能。以下是几种常见的实现方式: 基础图片组件封装 创建一个可复用的图片组件,支持默认图片、加载失败处理等基础功能…

vue项目实现方法

vue项目实现方法

Vue 项目实现方法 初始化项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 适合传统项目,Vite 适合现代轻量级项目。安装依赖后,通过命令行工具运行开发服务器。 # Vue C…

vue实现图片裁切

vue实现图片裁切

Vue 实现图片裁切的方法 使用 vue-cropperjs 库 vue-cropperjs 是一个基于 Cropper.js 的 Vue 封装库,专门用于图片裁切功能。 安装依赖: npm in…