How can I obtain distinct coordinates for clientX and clientX in JavaScript?

I am attempting to recreate a painting API using canvas. I am facing an issue where JavaScript only seems to retain one coordinate instead of two for drawing a rectangle.

Below is my code snippet:

var x_1;
var y_1;
var x_2;
var y_2;
var tab_coord;

function coord(evt) {
x_1 = evt.clientX;
y_1 = evt.clientY;
console.log("coordinate x_1: " + x_1 + " y: " + y_1);
tab_coord={'x_1': x_1, 'x_2':y_1};

canvas.addEventListener('click', second_coord);
}
function second_coord(evt) {
console.log(tab_coord);
x_2 = evt.clientX;
y_2 = evt.clientY;

console.log("coordinate x_2:" + x_2 + " y: " + y_2);
}

Even though the

console.log("coordinate x_1: " + x_1 + " y: " + y_1)
displays the first coordinate properly, JavaScript fails to store it in the tab_coord. Therefore, the console.log(tab_coord) shows the coordinates of x_2 and y_2 instead of x_1 and y_1 as intended.

Answer №1

It's inefficient to add the event listener on every click. Instead, you can use a single click handler to manage different actions.

Take a look at this:

This code creates a canvas that occupies the entire screen, sets x1 and y1 to undefined, attaches an event listener to the canvas when it loads, and executes shape functions based on the value of shape, which contains various types of shapes.

To create a rectangle, you need to calculate the width and height by subtracting x1 from x2 and y1 from y2.

If you use a two-click function, x2 and y2 are unnecessary.

var C=document.createElement('canvas'),
    c=C.getContext('2d'),
    x1,
    y1,
    shape='rect';
    C.width=window.innerWidth;
    C.height=window.innerHeight;
    C.style.cssText='position:fixed;top:0;left:0;';
    document.body.appendChild(C);
    C.addEventListener('click',handler,false);

function handler(e){
 shapes[shape](e);
}

shapes={    
 rect:function(e){
  x1? // Make sure x1 is not 0 because it will be interpreted as false.
  (c.rect(x1,y1,e.clientX-x1,e.clientY-y1),c.stroke(),x1=y1=false):
  (x1=e.clientX,y1=e.clientY);
 }
 //Add more shape functions here.Or fill whatever....
}

DEMO

http://jsfiddle.net/yY8EX/

Demo with circle

http://jsfiddle.net/yY8EX/2/

If you have any questions or need clarification, feel free to ask.

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

Searching in React can be done dynamically by referencing an array, similar to how the "LIKE" function works in SQL

Currently, I'm tackling an issue with a dropdown feature. My goal is to have the dropdown results sorted when the user enters something into the input field. The values in the dropdown are sourced from an array. For instance, codeList = [N1, N2, N3, ...

Beginner in React: Tips for modifying a component installed using npm

I have followed the guidelines provided in the URL (https://github.com/react-component/calendar) to add a component app to my dependencies. I successfully completed the installation, imported it into my project, and now it is visible and functional on my w ...

d3 bar chart with overlapping bars - define x and y coordinates

Here is a glimpse of the data I am working with: var students = [ {'race': 'Black', 'count': 7, 'year': 2004, 'allnames': ['G Brown', 'F Clarkson', 'E Miller', 'R Black& ...

What is the best way to retrieve all the values of a specific field from a store?

Is there a way to retrieve all the values of a specific field from a store without manually selecting each cell? In my grid, I am looking to extract all the values from a particular column directly from the store. Is this achievable without any manual sel ...

Optimizing Wordpress Plugin Configurations

I'm currently facing a challenge with saving the settings for a plugin that I am developing. The main objective of my project is to allow users of the plugin to choose a custom post type and have all the field types associated with that post object d ...

Continuously encountering the 403 Forbidden error when making a POST request to the

My react frontend is running at http://localhost:3000/ and express backend is at http://localhost:8080/ Whenever I attempt to submit the registration form, Chrome console shows an error: 'POST http://localhost:3000/api/users 403 (Forbidden)' ...

Tips for ensuring the footer always stays at the bottom of the page

I'm having an issue with keeping the footer pinned to the bottom of the page. I haven't applied any specific styles to the footer, just placed it at the end of the content. Everything looks great until there's a page with minimal content, ca ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

Guide to making an object with a value sourced from the redux store

I am looking to develop an object with custom getters and a key representing language. Depending on the language key, different values should be returned by the getters. This is specifically for a customizable language selection feature. As an example, one ...

When you try to create a popover, a cautionary message pops up indicating that $tooltip is no longer supported. It is

I need help with creating a popover that appears when hovering over an anchor tag. Here is the code I am using: angular: 1.4.2 ui-bootstrap :0.14.2 <div class="row" ng-repeat="endorsement in endorsements| filter: {category:categorySelected}"> &l ...

What is the best way to retrieve data based on conditions in React?

I'm currently learning React and trying to pass props from a parent component (table row) to a child Modal component. Inside the child component, I want to fetch data based on the props provided. I have created a custom hook called useFetch that store ...

When the mouse button is released or when an event listener is

I've been pondering a question that has yet to be fully answered. When I implement this technique to catch a mouse up event: <div onmouseup="/*Script to be executed*/"></div> Is it more efficient than this newer approach: <div id=" ...

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

Enhancing mongoose find queries in Node.js with dynamic conditions using both AND and OR operators simultaneously

I've been experimenting with adding dynamic conditions using the Mongoose library. var and_condition = { $and: [] }; var or_condition = { $or: [] }; and_condition.$and.push ({ "doc_no" : /first/i }) or_condition.$or.push ({ "doc_type" : /third/i } ...

Having trouble passing a jQuery string value into a Google Map object within a loop

How come the string gets lost inside the object during a loop? for (var i = 0; i < nrow.length - 1; i++) { displayNote = "<b>" + nfield[0] + "</b><br />" + nfield[1] + " " + nfield[2] + "<br /> " + nfield[7]; $('#googleMap& ...

Is it possible to update the total price on Shopify using CartJS and JavaScript?

Struggling to get my data updated using AJAX on my Shopify theme, and incorporating the CartJS plugin. The counter is working correctly, but there seems to be an issue with formatting the price. It does calculate the correct total, but fails to display the ...

Methods for validating React-Router navigation via history.push by utilizing Jest?

What is the best approach to unit test the following function that uses Jest to programmatically direct me to a specified page? function navigateToHome() { history.push('/home'); return { type: 'NAVIGATE_HOME', } } ...