Having trouble with the image URL not displaying correctly after drawing it on a canvas in Vue.js 3

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>

Answer №1

function generateImageFromCanvas({ canvasId }: { canvasId: string }): string {
  const canvas = document.getElementById(canvasId)
  const ctx = canvas.getContext('2d')
  ctx?.drawImage(videoElement, 0, 0, canvas.width, canvas.height)
  return canvas.toDataURL('image/png')
}

Answer №2

It is important to remember that you should place your toDataURL() within the img.onload callback, not after it. Simply setting img.onload = function() ... only sets up the callback function but does not execute it yet, resulting in an empty canvas initially:

img.onload = function () {
    const [x1, y1, x2, y2] = props.coordinates.split(',').map(Number);
    if (canvas.value) canvas.value.width = x2 - x1;
    if (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();
};    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flask - Issue with Bootstrap Navbar Dropdown not functioning properly on secondary pages

My navbar includes a dropdown link in base.html that is functioning properly on most pages, except for certain sub-pages. It works on: index/ dashboard/ users/user123/ However, it does not work on the following page (clicking "Dropdown Menu" does nothin ...

Issue with exporting VueJS-generated HTML containing checkboxes results in loss of checkbox checked state

In the template of my component, I have a checkbox code that looks like this: <div ref="htmlData"> <input type="checkbox" class="mycb" :id="uniqID" :disabled="disabled" v-model="cbvalue" > &l ...

I noticed that my regular expression is functioning correctly on regex101, but for some reason, it's

My search works perfectly on regex101 using this link: https://regex101.com/r/z8JCpv/1 However, in my Node script, the third matched group array[2] is returning not only the matching text but also everything following it. An example line from the source ...

Can you explain the purpose of the equals sign in ngRepeat?

Can you explain the significance of the equals sign in the ng-repeat attribute value? <li ng-repeat="person in people = (people | orderBy: firstname)"> rather than using: <li ng-repeat="person in people | orderBy: firstname"> I coul ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

The functionality of Styles in Material UI seems to be malfunctioning

I'm currently learning how to use Material UI for React, specifically focusing on makeStyles. Below is the JavaScript code I have: import React from "react"; import MenuIcon from "@material-ui/icons/Menu"; import EventNoteIcon fr ...

Generate downloadable files dynamically in response to a POST request

I'm exploring the idea of creating a file without actually storing it on the drive, just for the purpose of immediate download within a POST request. const specialRequests = async (req, res, next) => { // POST request ... // processing let ...

Performing a GET call within the configuration settings of AngularJS

I found a similar question here but unfortunately it didn't solve my issue. I am currently using Angular-UI's Google Maps API, which requires configuration as follows: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider ...

What is the measure of randomness created by Math.random?

I am trying to create a large random number without the need for cryptographic security. Therefore, I have opted not to use crypto.getRandomValues. Currently, my method of generating the random number is as follows: const random = length => Math. ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

Animating Page Transitions using Angular 2.0 Router

Seeking to implement animated transitions for new components using the onActivate method in Angular 2. A Plunk has been set up to demonstrate the issue at hand: http://plnkr.co/FikHIEPONMYhr6COD9Ou Here is an example of the onActivate method within a pag ...

Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve: create() { const map = this.make. ...

What is the best way to obtain a reference to the parent form element within an AngularJS directive?

Here is the HTML code I am working with: <form name="my-form"> <div class="col-sm-4"> <input type="phone" name="mobileNumber" ng-model="form.mobileNumber" value="0439888999" required> </div> </form> In addition, I ha ...

What is the best method for accessing the value of material-ui's Autocomplete Select component?

Is there a way to retrieve the selected value from a drop-down menu? I have the following code snippet, but it's logging an unexpected message to the console: MUI: The getOptionLabel method of Autocomplete returned number (0) instead of a string for ...

Adjusting parameters in HTML input range with the help of modifier keys

Working on an HTML interface that utilizes an input range element has led me to consider the challenge of fine-tuning control values without the use of special keys like Alt or Shift. It appears that achieving this functionality with pure HTML may be chall ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Using jQuery, identify when any of the elements within every function are missing

In my JavaScript file, I have the following code snippet: var aryYears= []; $(".year").each(function(){ aryYears.push($(this).val()); }) This allows me to pass an array of years as a parameter in the saveChanges function. I want to make ...

Exploring the world of unit testing in a store - any tips on getting it to work

I am currently working on a store.js file import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const mutations = { increment: state => state.count++, Changeloading(state, status) { state.loading = status }, Cha ...

Storing information in memory through the use of Javascript

i am interested in keeping this type of data consistently in memory. app_id admin_id url status 123 1 xyz.com 1 123 2 xyz.com 0 539 3 exmaple.com 1 876 4 new.com ...