Tips for creating an illustration in Vue.js

As I attempt to create an image using canvas, my browser throws this error at me:

Uncaught TypeError: Cannot read property 'drawImage' of undefined  at Image.img.onload (test.js:23)

To troubleshoot, I added some console.log() messages and here is the output:

args: 0 50 100
canvas: <canvas width=​"320" height=​"320">​
this.img.src: http://localhost:3000/img/img1.jpg
this.ctx: undefined
Uncaught TypeError: Cannot read property 'drawImage' of undefined  at Image.img.onload (test.js:23)

The root of the issue seems to be undefined "this.ctx", which perplexes me. Can anybody offer assistance? Below is the code snippet in question:

The JavaScript section:

var myVm = new Vue({
  el: '#draw-image-test',
  data: {
    items: [
      { id: 1, src: 'img/img1.jpg' },
      { id: 2, src: 'img/img2.jpg' },
      { id: 3, src: 'img/img3.jpg' }
    ]
  },
  methods: {
    drawItem(index, x, y) {
      console.log('args:', index, x, y);
      this.canvas = this.$refs.canRef;
      console.log("canvas:", this.canvas);
      this.ctx = this.canvas.getContext('2d');
      this.img = new Image();
      this.img.src = this.items[index].src;
      console.log('this.img.src:', this.img.src);
      this.img.onload = function () {
        console.log('this.ctx:', this.ctx);
        this.ctx.drawImage(this.img, x, y);
      }
    }
  }
});

The HTML portion:

<div id="draw-image-test">
    <canvas width="320" height="320" ref="canRef"></canvas>
    <button v-on:click="drawItem(0, 50, 100)">Draw item 0</button>
</div>

Answer №1

Save this component instance as a global variable called vm and utilize it within the callback in the following manner:

  console.log('this.img.src:', this.img.src);
  let vm=this;
      this.img.onload = function () {
        console.log('vm.ctx:', vm.ctx);
        vm.ctx.drawImage(vm.img, x, y);
      }
    }

Answer №2

Here is a helpful tip I found on the Vue.js forum:


The issue arises with the onload function, as it cannot be accessed directly within itself. To work around this, you can either use an arrow function or create a local variable to reference within the onload function.

this.img.onload = () => {
   console.log('this.ctx:', this.ctx);
   this.ctx.drawImage(this.img, x, y);
}

or

drawItem(index, x, y) {
const self = this;
.
.
.
this.img.onload = function () {
   console.log('ctx:', self.ctx);
   self.ctx.drawImage(self.img, x, y);
}

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

Retrieve the unique payment ID generated from the database and present it on the frontend

Greetings, I am currently working on integrating a payment processor and I require the automated generation of the corresponding payment ID in the backend. On the frontend side, I have implemented JS to request data from the backend, but I'm facing ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...

AngularJS directive doesn't refresh template when scope values are fetched dynamically through ajax requests

Attempting to give this question a precise title as possible, I find myself struggling with an issue in AngularJS. While trying to showcase my problem through a jsfiddle, it turned out to be too reliant on multiple files and not yet accessible online. So p ...

Tips for passing a JavaScript array to an MVC controller

In my asp.net application, I have implemented a functionality where users can order food. Additionally, there is an admin page where admins can login and create a menu for a specific week. I have successfully developed the "Menu maker" feature where all me ...

Issue with authentication and cross-origin resource sharing (CORS) when implementing Spring Boot, Spring Security, Vue.js,

Running on vue.js 3, Vite 4.0.2, axios 0.25.0, and spring boot (Starter 2.7.2). A backend has been created in spring boot while using vue.js3, vite, and axios for the UI. Now, I simply want to make a call to rest with axios. Before implementing these func ...

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

How big should the placeholder image be for the image area?

How can I create a loading image to replace a .gif while it loads? I need a placeholder image of about 325x325 (same size as the gif) to keep content in place. I've attempted using background: url() without success and haven't explored JS/jQuery ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...

Is it possible to exclusively focus on the specified data attributes?

Is there a method to specifically target the 'data-season' attribute with the value "winter"? This is my HTML: <li data-season="summer">summer <ul class="groups"> <li data-item="beach">beach</li> <li data-item ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Managing Actions in React-Redux: Understanding the Dispatch Function

While I am delving into the world of React, I stumbled upon an example that looks like this: //index.js const store = createStore(reducer) render( <Provider store={store}> <AddTodo /> </Provider>, document.getElementById(' ...

When transitioning between pages in Nuxt 3, the Three JS object fails to load

As I embark on this journey, I realize there is so much for me to discover. Despite my aversion to seeking help, I have scoured countless pages in search of a solution, but to no avail. It seems like a simple issue, yet I find myself struggling. Whenever ...

Issue with Vue: Calling method instantly when using :mouseover in v-for within a component

Whenever I try to incorporate :mouseover in a v-for loop within the <component>, I encounter an issue. The method assigned to the :mouseover event is triggered for each element, rather than just for the hovered elements. <Single-technology ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

How to retrieve multiple checked values from checkboxes in Semantic UI React

Trying to enable users to select multiple checkboxes in react using semantic-ui-react. I am new to react. Here is my code: class ListHandOver extends React.Component { state = { data: {} } handleChange = (e, data) => { console.log( ...

Load styles in Nuxt asynchronously to improve performance

Is there a way to load styles asynchronously on the website or insert them in the footer? I am currently using Nuxt version 2.0.0 Here's what I have tried so far: Adding a plugin in webpack called async-stylesheet-webpack-plugin. However, this res ...