Here is how you can create an image upload and crop component in Vue 3 composition API without any external libraries:
// ImageCropper.vue
<template>
<div>
<input type="file" @change="onFileChange">
<div v-if="image">
<img :src="image" ref="imageEl">
<div @mousedown="startCrop" @mousemove="crop" @mouseup="endCrop">
<canvas ref="canvasEl"></canvas>
</div>
<img v-if="croppedImage" :src="croppedImage">
</div>
</div>
</template>
<script>
import {ref, onMounted, reactive} from 'vue'
export default {
setup() {
const image = ref(null)
const imageEl = ref(null)
const canvasEl = ref(null)
const crop = reactive({
startX: 0,
startY: 0,
w: 0,
h: 0
})
let croppedImage = ref(null)
function onFileChange(e) {
const file = e.target.files[0]
const reader = new FileReader()
reader.onload = e => image.value = e.target.result
reader.readAsDataURL(file)
}
function startCrop(e) {
crop.startX = e.offsetX
crop.startY = e.offsetY
}
function endCrop() {
crop.w = Math.abs(crop.startX - crop.x)
crop.h = Math.abs(crop.startY - crop.y)
croppedImage.value = getCroppedImage()
}
function crop(e) {
crop.x = e.offsetX
crop.y = e.offsetY
drawCrop()
}
function drawCrop() {
const ctx = canvasEl.value.getContext('2d')
ctx.clearRect(0, 0, canvasEl.value.width, canvasEl.value.height)
if(!crop.w || !crop.h) return
ctx.strokeRect(crop.startX, crop.startY, crop.w, crop.h)
}
function getCroppedImage() {
const {startX, startY, w, h} = crop
const canvas = document.createElement('canvas')
const img = imageEl.value
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
ctx.drawImage(img, startX, startY, w, h, 0, 0, w, h)
return canvas.toDataURL()
}
return {
image,
onFileChange,
startCrop,
crop,
endCrop,
croppedImage,
imageEl,
canvasEl
}
}
}
</script>
The key points:
- Use
ref and reactive to manage state
- Load image on file change and display it
- On mousedown, save start crop position
- On mousemove, calculate crop region dimensions
- Draw crop region on canvas overlay
- On mouseup, crop image and display preview
Let me know if you have any other questions!