Drawing glitch on the canvas

Having trouble with drawing an image to a Canvas element and encountering this error:

Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1
textureLoadedstaticsprite.js:14
StaticSpritestaticsprite.js:21
(anonymous function)

Despite having both the CanvasRenderingContent and HTMLImageElement, I'm still puzzled.

This is the code in question:

    /**
  * Class for rendering static sprites such as trees and blocks
  */

function StaticSprite(args) {

    // Private Fields
    var texture = new Image();

    // Events
    function textureLoaded(context) {
        console.log(context);
        console.log(texture);
        context.drawImage(texture, 0, 0, 32, 32);

    }

    // Constructor

    // Add event listeners
    texture.addEventListener("load", textureLoaded(this.graphics), false);

    // Load texture
    texture.src = "img/assets/wall1.png";

    if(args != undefined) {

        // Set local fields
        this.x = args.x || this.x;
        this.y = args.y || this.y;
        this.z = args.z || this.z;
        this.width = args.width || this.width;
        this.height = args.height || this.height;

    }

    this.width = 32;
    this.height = 32;

}

// Inherit from GraphicsEntity
StaticSprite.prototype = new GraphicsEntity();

Also included is the base class GraphicsEntity for reference:

/**
  * Class for presentation of graphical objects.
  */

function GraphicsEntity(args) {

    // Private Fields
    var x = 0; 
    var y = 0; 
    var z = 0; 
    var width = 0; 
    var height = 0; 

    // Public Fields
    this.DOMElement = null; 
    this.graphics = null; 
    this.name = ""; 

    // Properties
    Object.defineProperty(this, "alpha", {

        get: function() { return parseFloat(this.DOMElement.style.opacity); },
        set: function(value) { this.DOMElement.style.opacity = value; }

    });

    Object.defineProperty(this, "height", {

        get: function() { return height; },
        set: function(value) {

            height = value; 
            this.DOMElement.setAttribute("height", height); 

        }

    });

    Object.defineProperty(this, "width", {

        get: function() { return width; },
        set: function(value) {

            width = value; 
            this.DOMElement.setAttribute("width", width); 

        }

    });

     Object.defineProperty(this, "x", {

        get: function() { return x; },
        set: function(value) {

            x = value; 
            this.DOMElement.style.left = Math.ceil(x) + "px"; 

        }

    });

    Object.defineProperty(this, "y", {

        get: function() { return y; },
        set: function(value) {

            y = value; 
            this.DOMElement.style.top = Math.ceil(y) + "px"; 

        }

    });

    Object.defineProperty(this, "z", {

        get: function() { return z; },
        set: function(value) { this.DOMElement.style.zIndex = parseInt(value); }

    });

    // Constructor

    // Get constructor values or use defaults
    if(args) {

        x = args.x || x;
        y = args.y || y;
        z = args.z || z;
        width = args.width || width;
        height = args.height || height;

    }

    // Create a new canvas element
    this.DOMElement = document.createElement('canvas');

    // Set position
    this.DOMElement.style.position = "absolute"; 
    this.DOMElement.style.left = x + "px"; 
    this.DOMElement.style.top = y + "px";  
    this.DOMElement.style.zIndex = z; 
    this.DOMElement.width = width;
    this.DOMElement.height = height;

    // Set opacity
    this.DOMElement.style.opacity = 1;

    // Get 2d canvas context
    this.graphics = this.DOMElement.getContext('2d');

}

Answer №1

texture.addEventListener("load", textureLoaded(this.graphics), false);

The current line attempts to attach the function returned by textureLoaded(this.graphics) as the event listener. However, since the function returns undefined, it doesn't work as expected.

To resolve this issue, you can modify the line to:

texture.addEventListener("load", textureLoaded, false);

Additionally, update the function declaration from:

function textureLoaded(context) {

To:

var context = this.graphics;
function textureLoaded() {

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

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Is there a consistent order required when calling React Hooks in each component render?

After implementing keyboard key or button navigation in a list of items, I encountered errors during the build phase that do not occur locally. The specific errors are as follows: Error: React Hook "useRef" is called conditionally. React Hooks m ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

Troubleshooting: jQuery animation for background-color doesn't function in Internet Explorer

I've been working on a website and I'm trying to create a navigation bar similar to the one found at . My goal is to have the navbar transition from transparent to a colored background as the user scrolls down the page. For this project, I am ut ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

What is the best way to implement an alert box in MVC without triggering a page redirection?

I have a specific requirement to display a custom alert box in order to confirm the user's intention to delete an item. Once the item is deleted, another alert box should appear confirming that the deletion was successful, prompting the user to click ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

Creating a collaborative storage space within a MERN project folder

Currently, I am developing an application using the MERN stack. The structure of my project repository includes both backend and frontend components: my-project/ ├── backend/ │ │ │ . │ . │ └── package.json ├── fronten ...

jQuery functions seamlessly on Chrome, Firefox, and Internet Explorer, unfortunately it does not work on iPhone

The code functions properly on desktop browsers, but encounters issues on iPhone devices. I would greatly appreciate it if you could take a look and help me identify the problem. What do you think could be causing this discrepancy? <ol style="margin: ...

It's essential to ensure that this property remains responsive, whether through the data option or by initializing the property for class-based components

This code snippet contains the template and path information. <template> <div class=""> <c1 :text="message1"></c1> <c1 :text="message2"></c1> </div> </templa ...

Guide to building an HTML table using an array of objects

Is there a way to dynamically create a table from an array of objects? Here's an example array: let data = [{name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3}] The desired HTML output shou ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Discovering the dimensions of images similar to Pinterest when fetching URLs with jQuery

Currently, I am in the process of developing a webpage that allows users to input a URL and extract images from it, similar to how Facebook, Pinterest, and The Fancy operate. Users input a URL and are provided with images that have a width greater than a s ...

What is the best way to identify the clicked cell?

I'm a JavaScript newbie trying to work with ExtJS 3.4. I've set up a basic tree with 3 columns and now I want to figure out which cell, row, or column has been selected. Currently, I'm following the example provided by Sencha at : var tr ...

Is it possible to set a minimum width for browser resizing?

https://i.sstatic.net/0qhjT.png Looking at the image provided, I'm doing a comparison of the minimum resizable widths between my website and GitHub's. Is there a way to enforce a minimum width limit on my website similar to GitHub's? I&apo ...

Validation of editable cells in a material table

I'm currently using Material Table for displaying table data and I'm looking to implement validation on the surname field. When the length of the surname is less than 3, I want to display an error message in red below the input field saying "too ...

Trigger an event upon completion of the angular $route.reload() function

I am encountering an issue where I need to refresh the route using the following code: $route.reload(); However, I also need to trigger a function just before the template is rendered again. For instance: $("#someTab").click(); Your help would be grea ...