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

Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released. However, I encountered an issue wit ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Issue: The n-api module is not being recognized due to an error stating "Cannot read property 'indexOf' of undefined"

After developing a C++ module using n-api and compiling it with cmake-js, I encountered an issue when trying to integrate it into my electron-vue application. Surprisingly, the module worked fine in other projects without electron-vue. However, every attem ...

What is the most efficient way to move queried information from one table to another while maintaining all data entries?

Currently, I am working on a small POS project. In this project, I have two tables. The main purpose of the first table is to retrieve products from a search box with two column names retrieved from the database. If the products are found, I want to be abl ...

Traversing a JavaScript array with multiple dimensions containing markers created with Google Maps APIs

I have a single array where I store all of the Google Maps marker objects. Currently, I am working on creating a function to remove all markers from the map that are in the array, but I'm facing issues with the loop. First, I add each marker to the a ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Is there a specific code repository available that can verify and transform blog comments into XHTML strict format?

I'm currently developing a PHP website that allows users to make comments similar to a blog, and I am specifically interested in restricting the use of certain HTML tags. Is there any existing library that can process user comments and output valid XH ...

Transmitting form information to a nested page within a div container

This is my fourth attempt to seek an answer to this question, as I've faced downvotes in previous attempts. So here we go again. I am trying to send data from a hidden input within a form using ajax. The value of the hidden input is generated by a php ...

Find the quantity of items in each list individually and add them to a new list

Seeking a solution for a seemingly simple issue. I am attempting to calculate the number of list items and then add this count to the list in the parent div. The problem lies in the fact that it always displays the value of the last item in the list. For i ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...

When using Vue computed, an error is thrown stating "Issue in rendering: 'InternalError: too much recursion'" if the same key is referenced in computed

As a newcomer to Vue, I wanted to track how many times a function in the computed section gets called. To achieve this, I created the following component: const ComputedCounter = { name: "ComputedCounter", template: ` <span>{{ value } ...

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

Error in jQuery: Null property causing TypeError when reading 'text'

Issue: I have a modal form that is loaded via an ajax call. Inside the modal, there is a span element containing an email address. I am trying to capture the value of this span element using JavaScript. Currently, I have a button click event that triggers ...

VueJS Vuetify automatically centers default content

Vue cli version @ 5.0.6 | Vuetify version: [email protected] I have been utilizing Vue.js and Vuetify for some time now, and I can't shake the feeling that not all Vue.js/Vuetify components default to centered alignment. I recently initialized a ...

Managing several drop elements using class dynamically

I am facing a challenge in combining drag and drop listeners into one function to create dynamic zones with the same class. This will allow me to call a single function for uploading files. The upload function is currently working correctly, but I need a ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

Is it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...