As I attempt to crop an image using the ctx.drawImage() function with specific coordinates, I encounter an issue where the canvas's dataURL does not reflect the cropped image. The drawn image appears on the DOM, but the base64 image returned from the canvas is empty.
Below is the code snippet of the component responsible for displaying the canvas and the image extracted from the canvas's dataURL:
<template>
<canvas ref="canvas" :style="{ width }"></canvas>
<img alt="canvas image" :src="imageURL" :style="{ width }" />
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
const props = withDefaults(
defineProps<{
imageSrc: string;
coordinates: string;
width: string;
}>(),
{
width: '120px'
}
);
const imageURL = ref<string>('');
const canvas = ref<HTMLCanvasElement | null>(null);
onMounted(() => {
if (!canvas.value) return;
const ctx = canvas.value.getContext('2d');
const img = new Image();
img.src = props.imageSrc;
img.onload = function () {
const [x1, y1, x2, y2] = props.coordinates.split(',').map(Number);
canvas.value ? (canvas.value.width = x2 - x1) : '';
canvas.value ? (canvas.value.height = y2 - y1) : '';
ctx?.drawImage(img, x1, y1, x2 - x1, y2 - y1, 0, 0, x2 - x1, y2 - y1);
};
imageURL.value = canvas.value.toDataURL();
});
</script>