Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c";
ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH);
ctx.fillStyle = "#fff";
ctx.fillText("Click here to play again.", sampleTextX, sampleTextY);

This clickable rectangle has been giving me some trouble. While I found a potential solution here, the event listener for the mouse click isn't working as expected. Here is the code snippet I'm using:

canvas.addEventListener("click", getClickPosition, false);

function getClickPosition(e) {
    var xPosition = e.clientX;
    var yPosition = e.clientY;
    if ((sampleRectX <= xPosition) && (sampleRectX + sampleRectW >= xPosition) && (sampleRectY <= yPosition) && (sampleRectY + sampleRectH >= yPosition)) {
        if (lose === true) {
            playAgain = true;
        }
    }
}

In case it helps, my code structure is like this:

//Variables here
...

//Objects (player, enemy...)
...

function main() {
    ...
}

function init() {
    ...
}

function update() {
    ...
}

function draw() {
    ...
    if (gameStarted === true) {
        ...
        if (lose === true) {
            ...
            ctx.fillStyle = "#9b958c";
            ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH);
            ctx.fillStyle = "#fff";
            ctx.fillText("Click here to play again.", sampleTextX, sampleTextY);
        }
    }
}

main();

As a beginner in coding, I apologize if my question seems too basic.

Answer №1

((sampleRectX < xPosition) && 
 (sampleRectX + sampleRectW > xPosition) && 
 (sampleRectY < yPosition) && 
 (sampleRectY + sampleRectH > yPosition)
)

You were very close, but you missed a parenthesis at the end.

When analyzing the mouse event returned from the event listener, it's important to check for different values each time.

I initially used e.clientX like you did, but it didn't work as expected because my canvas wasn't positioned at 0,0. Instead, I had to use e.offsetX and e.offsetY to obtain the correct values.

Although I'm unsure about the exact meaning of all coordinates in the mouse event, I will research further and update my response accordingly.

Hopefully, this adjustment resolves your issue.

If you encounter any doubts, consider using console.log() for debugging purposes to understand what is happening with the API responses.

(If the problem persists, insert console.log() statements throughout your code to identify any potential execution problems.)

I have created an example fiddle for you: http://jsfiddle.net/cxyTV/1/

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

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

Perplexing behavior displayed by non-capturing group in JavaScript regular expressions

Here's a straightforward question for you. Regex can sometimes get tricky, so thank goodness for simplifying things... In the URL, there's a query parameter labeled ?id=0061ecp6cf0q. I want to match it and only retrieve the part after the equal ...

Failed to retrieve the item stored in the local storage

I am encountering an issue where I am unable to retrieve an item from local storage and display it. In store.js, I am trying to get the shippingAddress from local storage but it is not showing up in the form. Although I am able to set the shippingAddress i ...

Generating an array of quarter numbers and year based on the current date in Node.js using Moment.js - a simple guide

I need to generate an array of quarter numbers and year numbers based on the current timestamp in Node.js. For instance, if the current quarter is Q1 and the year is 2020, I want to create an array similar to the one below. quarters = ['Q2-2019' ...

Swap out a module with a different one in a node.js environment

In the scenario where a node.js application consists of numerous files referencing a particular module (like underscore), and there is a need to replace that module with another (such as lodash), the typical approach involves globally replacing the names a ...

Guidance on loading JSON array information into highcharts using AngularJS

I am working on a project in Play Framework (play-java) where I need to display a bar graph using Highcharts. The Java API returns data in JSON format with a field called 'name' containing values like 'Data', 'Gadgets', ' ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

A guide to creating an HTTPS request using node.js

I am currently in the process of developing a web crawler. Previously, I utilized the following code for HTTP requests: var http=require('http'); var options={ host:'http://www.example.com', path:'/foo/example' }; ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

generate a cookie within a pop-up window

Can someone help me figure out why my Modal Window with a cookie to display only once isn't working? I followed this tutorial at . Here is the link to my website: Here is my code: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" a ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

Is it possible to include a base url for imports in React JS?

Conventional method for adding imports: import Sample from ‘../../../components/signup’ I want to simplify imports by removing the front dots and slashes: import Component from ‘components/signup’ Is there a way to set a base URL for imports to ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Exploring the benefits of utilizing TypeScript's async await feature within the Node

I've encountered a challenge trying to accomplish the following tasks simultaneously: Developing in Node.js Coding in TypeScript Implementing async await Facilitating debugging Background: In my TypeScript-based Node.js project, I am incorporating ...

What is the best way to ensure that this <span> maintains a consistent width, no matter what content is placed inside

So here's the deal, I've got some dynamically generated html going on where I'm assigning 1-6 scaled svgs as children of a . The span is inline with 2 other spans to give it that nice layout: I want these "boxes" to all be the same width be ...

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...

Include a new route in the Vue.js router dynamically during runtime

I am in the process of developing an application and I want to incorporate extensions into it. These extensions will have their own Vue components, views, and routes. Instead of rebuilding the entire app, I am looking for a way to dynamically add these new ...

Working with variables passed from Node.js in Jade processing

Currently, I have a situation where my script is sending a matrix that looks like this: [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. After sending it using res.send(JSON.stringify(dataArray)); and viewing it in jade with h1#results, I can see that the format appears ...