Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first time, but issues arise after resizing. The click coordinates become incorrect and the behavior degrades. It seems like there's a backlog of click events accumulated from all the times the screen was resized.

For the complete code snippet, visit stackblitz

The resize function

@HostListener('window:resize', ['$event'])
    onResize(event) {
      this.innerWidth = window.innerWidth;
      this.innerHeight = window.innerHeight;
      this.canvas.width = this.innerWidth;
      this.canvas.height = this.innerHeight;
      this.cleardraw();
      this.draw();         
    }

      cleardraw(){
    var ctx = this.canvas.getContext('2d');
    ctx.clearRect(0, 0, this.innerWidth, this.innerHeight);

   }

The draw function

draw() {

  // Code for drawing seats...

}

The click event function

this.renderer.listen(this.canvasRef.nativeElement, 'click', (event) => {
    let cX = event.layerX;
    let cY = event.layerY;

    // Code for processing click events...

});

Answer №1

The issue arises from the fact that every time you adjust the size, renderer.listen gets invoked again resulting in multiple events being triggered with a single click.

To rectify this, it is crucial to ensure that you clear the listener before adding a new one.

// Validate if the reference exists
if (this.reference != null) {
    this.reference; // Clear the listener
}

// Keep a record of the listener
this.reference = this.renderer.listen(this.canvasRef.nativeElement, 'click', (event) => {

Take a look at this modified StackBlitz

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

Can the default Bootstrap classes in the ExtLib application layout control be modified?

I am currently using the responsive Bootstrap theme in combination with the application layout control in extlib, but I have been unable to locate any documentation on whether it is possible to modify the predefined Bootstrap classes. In the example below ...

When I toggle the div to close on mobile, I want it to show on desktop

My attempt at creating a toggle button to hide and show content was not successful. I struggle with coding in Javascript/Jquery. In the desktop view, the description displays perfectly (see image here), but in mobile view, there is a button to toggle hidi ...

How about: "Interactive web form featuring customizable options to determine which fields are shown?"

How can I design a dynamic web form that changes based on selected options? This form will include standard fields as well as customized fields depending on the user's previous selections. There are approximately 120 different combinations of forms p ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...

The error with removing the form field control in Angular 7 persists

I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure of the FormGroup: ngOnInit() { this.basicInfo ...

Creating HTML input elements dynamically using Javascript

<body> <form action="insertquestion.php" method="POST"> <script> function generateInputs(){ var prefix = "answer"; var number = 1; for(var i = 0; i < 5; i++){ ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

The error message "printer.node is not a valid Win32 application" indicates that the

I created a node API for my Angular application that utilizes the node-printer package to print PDF files generated by node. However, when I attempted to run my application using nodemon, an error occurred. Error message: "node printer.node is not a val ...

Wrong method executed when trying to use Angular http put

I am facing an issue with my http.put wrapper where it is calling the incorrect PUT overload. I specifically need the one that returns Observable<Object>, but instead it is calling Observable<ArrayBuffer>. Here is the code snippet for my http.p ...

Customizing alert message styles in Java script: Changing color and font of specific parts

I have been attempting to change a specific part of text to be bold and displayed in red color. Unfortunately, this does not seem to work on Microsoft Edge. Here is my code: alert("Hi how are you my friend"); The section that needs to be formatted: "fri ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

Exploring the nativeElement property of a customized Angular HTML element

In my Angular Jasmine Unit Test, I am testing a third-party slider component in my application using the following code snippet: Here is the HTML: <ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch> And her ...

I am constantly encountering this issue: Uncaught TypeError - It's impossible to read properties of undefined (specifically 'image') in PromptCard at PromptCard.jsx on line 37

Click here to see the error message This is the code for my components\PromptCard.jsx file: "use client"; import { useState } from "react"; import Image from "next/image"; import { useSession } from "next-auth/reac ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

Prevent the use of unnecessary object properties

Currently, my project involves using Typescript and React in conjunction with Material-UI. Specifically, I am utilizing Material-UI's styling solution, which implements CSS in JS methodology in a Hook-like manner as outlined in their documentation: co ...

The issue with Postman Express.js Response Body not displaying any content is quite common

I've been struggling with this issue for a whole day and I just can't seem to find a solution. My node app is extremely simple. const express = require("express"); const port = 3001; const app = express(); app.use(express.json()); app.pos ...

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...