Manipulating and managing objects on the canvas by choosing and unselecting them, then relocating to the coordinates of

This code snippet demonstrates how to select a drawn object on a canvas by clicking, and then move the object to another position with a double click or deselect it with a double click before/ after moving.

I have been struggling for days to figure out how to apply this functionality to all objects within a class or an array using loops (through the class constructor + prototypes). My goal is to enable the selection or deselection of any object on the screen.

Any assistance would be greatly appreciated. Thank you.

Answer №1

Let's tackle this task with a logical approach.

  1. Compile a list of drawable items.
  2. Assign states to each item.
  3. Determine if an item is clicked on or not.
  4. Implement movement and toggling for selected items.
  5. Manage clearing and drawing on the canvas.

I've put together a simple fiddle to illustrate the concept:

let context = $("canvas")[0].getContext("2d");
let elements = [
new element(20, 20, 20, 20, "green"),
new element(45, 30, 30, 30, "red"),
new element(80, 40, 50, 50, "blue"),
];
let mousePosition = {
x: 0,
y: 0,
};
let selected;

function element(x, y, height, width, color) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.color = color;
this.selected = false;

this.draw = function(context) {
context.strokeStyle = (this.selected ? "black" : "white");
context.fillStyle = this.color;
context.beginPath();
context.lineWidth = 2;
context.rect(this.x, this.y, this.height, this.width);
context.fill();
context.stroke();
}

this.move = function(x, y) {
this.x = x;
this.y = y;
}
}

//Select Function
function get_select(x, y) {
let found;

$.each(elements, (i, element) => {
if(x > element.x
&& x < element.x + element.width
&& y > element.y
&& y < element.y + element.height) {
found = element;
}
});
return (found);
}

// Handle selection & Movement.
$("canvas").click(function() {
let found = get_select(mousePosition.x, mousePosition.y);

Clear();
// Toggle Selection
if (found && !selected) {
found.selected = true;
selected = found;
} else if (found === selected) {
found.selected = false;
selected = null;
}

// Move
if (!found && selected) {
selected.move(mousePosition.x, mousePosition.y);
}
Draw();
});

// Record mouse position.
$("canvas").mousemove((event) => {
mousePosition.x = event.pageX;
mousePosition.y = event.pageY;
});

//Draw ALL elements.
function Draw() {
$.each(elements, (i, element) => {
element.draw(context);
});
}

function Clear() {
context.clearRect(0, 0, $("canvas")[0].width, $("canvas")[0].height);
}

// Start.
$(document).ready(() => {
Draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<canvas></canvas>
</body>
</html>

Hopefully, this guide proves useful to you!

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

The unfortunate error of 'MODULE NOT DISCOVERED' has arisen, as the module cannot be located

Currently working on resolving the pathing issues: This is how my folder structure appears: /www/html/ /database/ databaseConnection.js /scripts/ LoginPageScript.js server.js index.html In the database js file, there is the following code snippe ...

Vue initialization encounters an issue with starting 'marker-animate-unobtrusive' package

I am encountering an issue with marker-animate-unobtrusive and keep receiving the following error: https://i.sstatic.net/Y69xK.png While browsing through SO, I came across a post discussing the importance of requiring the file after Google has loaded. Ho ...

Looping through an array and adding its elements to a dictionary using JavaScript

I am struggling to figure out how to iterate over a dictionary with values in the form of arrays and then organize those values into a new dictionary. I am unsure of the steps needed to achieve this. Below is the data I need to iterate through: { t: [&quo ...

Ways to emphasize a specific row within a table for special occasions

I have limited knowledge of CSS and JavaScript, but I am looking for a way to create a notification highlight that functions similarly to when someone comments on a Facebook post. When clicked, it should direct me to the specific comment with a temporary h ...

Ensure that data is accurately confirmed using an alternative mode within react-hook-form

Currently utilizing react-hook-form with the primary validation mode set to "onChange": const formMethods = useForm({ mode: 'onChange' }) I am looking to modify the mode property for a specific input nested within a Controller, but I am unsure ...

Exploring the functionality of adding a table by clicking on each column in Highcharts using Reactjs

Utilizing highcharts-react-official for highcharts implementation, I have successfully displayed a column graph. However, the requirement now is to show a table containing detailed information related to each clicked column, including hyperlinks. I am stru ...

How can I make the onclick event work for all items instead of just the first json item that changes?

I am a beginner in JavaScript and I am not allowed to use jQuery or HTML in my assignment. I am trying to change the color of different items in my JSON when clicked, but it only works for the first item in the list. When I try to apply it to the second it ...

Assistance needed for disabled JavaScript

I'm currently working on a small application where I need to display some text wrapped in 3 divs. The goal is to only show one div at a time and provide users with prev and next buttons to switch between them. However, when JavaScript is disabled, I w ...

How to Send Hidden Input Element Values to Controller?

On my ASP.NET MVC page, I have multiple hidden input elements that store integer values. They can be found using the selector $('table#ratings input[name=newReviewRatings]'). I'm wondering if it's feasible to use $.post() to send the i ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Issues with the File function in Cordova/Phonegap impacting functionality

I am eagerly anticipating the day when the file function in Cordova finally starts working for me! This particular section of code functions perfectly on Chrome (hooray!), but unfortunately not within the Android app: function errorHandler(e) { var msg ...

Playing videos with ReactJS: Learn how to implement a feature where a video is displayed in the center of the screen

I have a list of 20 items in my maplist, which are actually 20 videos. My goal is to play the video that appears in the center of the viewport and pause all others, maintaining this behavior while scrolling: const [reels, setReels] = useState([] ...

invoking a function through prototype

<script> var Nancy = function(){ this.name = 'nancy' } Nancy.prototype.getNancy = function(){ alert(this.name); } Nancy.prototype.getNancy(); function Bob(){ ...

Is it possible to eliminate certain JavaScript code by clicking on something?

I've been searching for a solution to this issue without any luck. Currently, I have two main JavaScript functions running on a website I'm developing. One is for lazy loading images and the other is for smooth scrolling to an anchor link at the ...

What are the steps involved in searching for a document in MongoDB with Mongoose?

Looking to query MongoDB documents that contain an array of objects and remove a specific object with a particular value? Here are some tips: Check out this example of a document schema: const mongoose = require("mongoose"); const LibrarySchema ...

"Unlocking the Power of Node Modules: Ensuring Libs are Access

Imagine a scenario where project B relies on a node module called A. The structure of module A is as follows: ./node_modules/A ./src ./shared bar.js foo.js .... etc .... Within project B, I want to utilize bar.js a ...

Incorporating a JavaScript object into a DataTables JSON structure: A practical guide

I have integrated the datatables jQuery plugin into my project and I am looking to streamline the process by creating a shared function to easily call a datatable from multiple pages without duplicating code. To achieve this, I am attempting to define the ...

Rejuvenate a just-launched window.open starting from the about:blank

After receiving data from an ajax result, I am trying to open a pdf in a new window. However, the pdf viewer is only displayed if I manually resize the window (using manual hotspot resizing). How can I ensure that the contents display properly in its popu ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Unable to show JSON data on the console

I am attempting to retrieve a large array of JSON objects from a remote server. The server-side is based on Node.js + redis. Here is my ajax query: $.ajax({ crossDomain: true, type:"GET", contentType: "application/json", url: "http://****. ...