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

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

I am only able to trigger my AJAX request once

Whenever I click on a checkbox, an ajax function is triggered. This function sends a query string to a PHP script and returns relevant HTML. Strangely enough, if I first select a dropdown option and then check another checkbox along with the previous one ...

What is the best way to extract individual objects from several arrays and consolidate them into a single array?

Currently, I have a collection of objects stored in a variable called listOfObjects. They are not separated by commas because I utilized the Object.entries method to extract these values from another array. console.log(listOfObjects) outputs { q: 'L ...

Is it possible to dynamically change a form's input value using a JavaScript keyup function based on input from other form elements?

My form utilizes the keyup function to calculate the total value of 3 input fields by multiplying them and displaying the result. Below is a fiddle showcasing this functionality: $(document).ready(function () { $(".txtMult1 input").keyup(multInp ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

What is the best way to retrieve distinct id values from a form in Rails when sending a DELETE request via AJAX?

I am determined to grasp the intricacies of AJAX and how it operates, hence, I prefer not to use "remote: true" for this task. The issue at hand is that despite attempting to send a DELETE request to the server using a form input, each submission results i ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

Enabling the acceptance of blank values within an HTML5 date input field

When using an HTML5 date input for a field that corresponds to a nullable datetime column in the database, how can one avoid setting an empty value in the input field? In my AngularJS application, the ng-model is connected to a scope variable with an init ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

Interactive PayPal quick checkout feature

Currently, I am in the process of developing an online store for a personal project and this piece of code is extracted from my application. <div class="row"> <script src="https://www.paypalobjects.com/api/checkout.js"></script> {{#e ...

What is causing the net::ERR_CONNECTION_RESET in Node JS and ExpressJS?

Our application, built on ExpressJS and NodeJS, is hosted on a Linode server and served at port 3000. Although the app has been functioning well for a year, we have recently encountered consistent connection errors. The errors vary, but they are mostly re ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

Monitoring data updates within an Angular directive

Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable? Currently, I am loading a basic dataset from a JSON file usin ...

Toggle element visibility upon clicking

<table id="selectsupp"> <tr> <td> <select id="category"> <option value="display" readonly="true">-Shop By Category-</option> <option value="all">All</option> <option val ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

Perform a JSON POST request from an HTML script to a Node.JS application hosted on a different domain

In an attempt to send string data via a post json request using JavaScript within an .erb.html file, I am facing the challenge of sending it to a node.js app on another domain that uses express to handle incoming requests. After researching online, I have ...

I am looking to send a combination of string and HTML data to the controller when using the Summernote editor in MVC

As a beginner in MVC development, there are certain aspects that I am still struggling with. Currently, I am using the Summernote Editor to compose blog posts and Ajax to submit them. However, I encountered an issue when trying to send both HTML data from ...