How to reference Canvas elements in VueJS components from a different file

In my @vue3/cli project, I am facing a straightforward problem that I can't seem to find a solution for.

I have two components within the same view hierarchy. One component displays webcam video in a video tag, while the other component contains an HTML5 canvas. My goal is to render a portion of the video on the canvas component, but I'm unsure how to send the video image from one component to the other.

Home -->
        WebCam.vue  
        Canvas.vue
    

I attempted to send the video data from the WebCam component to the Canvas component using:

this.emitter.emit('cam-image', {
                   id:'video',
                    image: this.video 
                })
    

Despite using mitt for event emitting, this approach did not work as expected. The entire video tag is being logged in my console.

this.emitter.on("cam-image", data => { 
                     console.log(data.image)
                        this.canvasContext.drawImage(
                          data.image,
                         0, 0,
                         300, 150,
                        0, 0, this.canvasWidth, this.canvasHeight
                    );
                })
    

As an alternative, I considered accessing the refs from the Canvas component within the WebCam component to directly render the image from there.

Answer №1

If you're looking to share a variable between components, there are a few options available. One simple way is to use a global variable. This can be achieved by creating a global reactive instance, like the example below:

// global.js
import { ref } from "vue";
export const sharedVariable = ref(null);

Once you have defined the global variable, you can import and use it in your components like this:

<template>
  ...
  <div v-if="$sharedVariable.value">Shared Content</div>
  ...
</template>

<script>
  import { sharedVariable } from "global.js";

  export default {
    setup() {
      // make the variable available to the template
      return {
        sharedVariable 
      }
    }
  }
</script>

You can repeat the same process for other components that need access to the shared variable.

Another approach is using provide/inject to pass data down to child components only when needed. This method ensures that the shared data is scoped properly and doesn't require a global instance:

In the parent component:

<script>
provide() {
  return {
    sharedVariable: sharedVariable
  };
}
</script>

And in the child component:

<script>
inject: ['sharedVariable']
// now you can use sharedVariable within this component
</script>

This approach mimics the functionality of the context API in React and provides a clean separation of concerns for your components.

For a practical example and live code demonstration, check out the jsfiddle link.

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

Mapping with Angular involves iterating over each element in an array and applying a function to each one

I am working with an API that provides data in a specific format: {"data": [ { path: "some path", site_link: "link", features: ['feature1', 'feature2'] } ... ]} Now, I have a service called getSites() ge ...

Fire the click event following the parsing of the HTML page

Is it possible to programmatically navigate to a URL, retrieve the response, and then activate the JavaScript click event of an HTML element within that response? For example, if the response contains an element like this: <div id="test">Click me< ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

individualized django models field for each user

Is it possible to create a boolean field in the post model to track if a user has liked a post? This field should only be changed by the respective user and not affect others. For example, if user 1 likes a post, it should show as true only for that user ...

transition from jQuery to Zepto

I have been utilizing multiple jQuery plugins in my codebase... Recently, I decided to switch over to Zepto, but encountered an issue Uncaught TypeError: Object function (a,b){return A.init(a,b)} has no method 'data' when checking the console ...

Updating the rotational pivot of an object following a positional shift

After moving my object with the "w" key and then rotating it with the "x" key, I noticed that my object rotates around the world origin instead of its own center. How can I update the object's pivot after moving it? I've come across suggestions t ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Perform an update followed by a removal操作

I've been facing a persistent issue that has been troubling me for quite some time now. The setup involves a database in MariaDB (using WAMP) and an API in ExpressJS. Within the database, there are two tables: "menu" and "item," with a foreign key rel ...

Javascript - combining properties using "concatenation"

I'm currently pulling data from JSON for a three.js scene. My goal now is to transform data such as "position.x : 1" into object[ position ] [ x ] = 1. The syntax object [ key ] = value isn't effective in this case. This would result in object[ ...

Is there a gentle approach to transferring calendar event variables in JavaScript?

The example provided below showcases a @model that contains data. To utilize specific portions of the data, I have transformed it into a Json object using Json.Serialize. This was necessary because the events:[ ] section requires data in a particular form ...

Build a custom loader in Next JS that leverages Webpack to dynamically map URL paths to specific components

I am looking to implement a custom loader in Next.js that leverages Webpack through the next.config.js configuration file. This loader should route Blog.js for the /blog route and Tutorial.js for the /tutorial route. The MDX data is stored in the pages/ d ...

Retrieve the nickname of the user's guild

There is an issue with my discord bot where I am unable to access the nicknames of users. I can easily get the username, but the nickname is not accessible: client.on('interactionCreate', async interaction => { var username = interaction.user. ...

The navigation on my mobile collapses whenever I use the Hello bar app

I am facing a problem with my Shopify theme. I recently installed an app called "Hello Bar" to show offers on all pages, but it seems to be incompatible with my theme. The developers of the app suggested adding the following code to my CSS file: @media ...

When I click on the event target, it selects the button within the span. What is the next step I should take

I have a button element that contains a span, and I want to extract the value associated with the button when it is clicked. However, if I click on the span inside the button, I am unable to retrieve the desired value because the event target points to the ...

Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original s ...

What could possibly be the issue with this mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_HOST_URL + ima ...

Troubles encountered during the installation of Visual Web Developer 2010?

Here is the situation I'm facing: After encountering some issues with PHP while working on an ASP.net project, I decided to reinstall everything. The installation of Apache, MySQL, and PHP went smoothly, but now I seem to be facing some problems. I ...

Ways to select a single checkbox when other checkboxes are selected in JavaScript

var select_all = document.getElementById("select_all"); //reference to select all checkbox var checkboxes = document.getElementsByName("testc"); //retrieving checkbox items //function to select all checkboxes select_all.addEventListener("change", function ...

The issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...