Shifting around haphazardly positioned crates using the cursor

I've successfully developed a program that fills the canvas with randomly positioned boxes of various colors. While this task was relatively easy, I'm now facing a challenge in moving these colored boxes around using my mouse. Additionally, I want the cursor to maintain a constant distance from the top-left corner. Below is my code, any assistance would be highly appreciated!

window.onload = init;

function init() {

var x= Math.floor(Math.random()*400);
var y= Math.floor(Math.random()*400);

var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");

canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
var context = canvas.getContext("2d");

// Draw 100 rectangles
for(var i=0;i<100;i++){
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    context.fillStyle = color;

    // Each rectangle is placed within the window dimensions and sized at 50x50    
    context.fillRect(Math.random()*window.innerWidth, 
    Math.random()*window.innerHeight, 50, 50);
}

document.body.appendChild(canvas);

}

var mousePiece = null;

function init2() {
var cx = document.querySelector("canvas").getContext("2d");
addEvent(cx, "mousedown", mouseGrab, false);
}

function mouseGrab(e) {
var evt = e || window.event;
mousePiece = evt.target || evt.srcElement;

addEvent(document, "mousemove", mouseMove, false);
addEvent(document, "mouseup", mouseDrop, false);
}

function mouseMove(e) {
var evt = e || window.event;
var mouseX = evt.clientX;
var mouseY = evt.clientY;

mousePiece.style.left = mouseX + "px";
mousePiece.style.top = mouseY + "px";
}

function mouseDrop(e) {
mousePiece = null;
removeEvent(document, "mousemove", mouseMove, false);
removeEvent(document, "mouseup", mouseDrop, false);
}

function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
    object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
    object.addEventListener(evName, fnName, cap);
}

function removeEvent(object, evName, fnName, cap) {
if (object.detachEvent)
    object.detachEvent("on" + evName, fnName);
else if (object.removeEventListener)
    object.removeEventListener(evName, fnName, cap);
}

function getStyle(object, styleName) {
if (window.getComputedStyle) {
    return document.defaultView.getComputedStyle(object,  
null).getPropertyValue(styleName);
} else if (object.currentStyle) {
    return object.currentStyle[styleName]
}
}

Answer №1

If you're looking for a fun interactive feature, I highly recommend checking out JQuery UI draggable. To give you a taste of what it can do, I created a colorful demo in this JS Fiddle. The possibilities with JQuery UI are endless, so take a look at the documentation to see all the amazing things you can achieve.

$( document ).ready( function () {
for ( var i = 0; i < 50; i++ ) {
    var randomColor = Math.floor(Math.random()*16777215).toString(16);
    var ranNum = Math.round( Math.random() * 65 )
    $( ".boxHolder" ).append( '<div class="pos' + i + ' draggable ui-widget-content"></div>' )
    $( ".pos" + i ).css({
        "background" : "#" + randomColor,
        "top"        : 10 * i + "px", 
        "left"       : ranNum * 6 + "px"
    })
}
})

$( function() {
   $( ".draggable" ).draggable()
})

Answer №2

Unfortunately, the canvas element acts as a pixel map, meaning that any drawings made on it are essentially modifying pixel values rather than creating separate HTML elements with unique identifiers. This makes it challenging to manipulate these drawn items using standard event.target methods.

On a brighter note, there exist canvas libraries that provide an object-oriented approach to working with canvas elements, allowing for better control and manipulation of individual items. One such library is fabric.js, which showcases various functionalities available for canvas operations. It's worth exploring different options to suit your needs!


Addtionally, there are two considerations when dealing with random color strings:

  1. To prevent getting an excessively large value like 2^24, consider using Math.floor instead of Math.round (as also pointed out in ALFmachine's response).
  2. When defining CSS colors using hex digits, ensure you have either 3 or 6 hex digits preceded by '#'. To avoid parsing issues, pad the hex digits with '0' to meet the required 6-digit format.

Alternatively, you can generate a CSS rgb() color string by using three random integers within the range of 0 to 255.

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

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function. Take a look at my ngOnInit method, ...

I encountered an error with the TS1003 code in Angular because an identifier was expected on the throw import statement. Upon further investigation, I realized that the issue originated from

I came across this piece of code: import { Observable, throw} from 'rxjs'; An error message popped up saying identifier expected: ERROR in config/config.service.ts(3,22): error TS1003: Identifier expected. The error appears to be related to ...

The Angular project failed to run properly following the ng build command

Just started working with Angularjs 2 and encountered an issue after running ng build. The compiled files were placed in the dist folder, but when I checked the index.html file within that folder, all the scripts had missing references even though they w ...

Issues with closing Foundation 6 off-canvas feature

Here is a link that I have: If you click on the skip button in the middle, it will take you to the next slide where Foundation 6 off-canvas is implemented. The header containing the toggle button for the off-canvas menu is located outside of the menu its ...

Exploring geometric materials within the THREE.js framework

I'm currently working on creating a geometry in THREE.js: var dotGeometry = new THREE.Geometry(); dotGeometry.dynamic = true; var createDot = function (group, x, y, z){ group.vertices.push(new THREE.Vector3( x, y, z)); } var width = 300; var he ...

Best Practice for Delivering JavaScript Files with Node.js Ajax?

In my current project, I am developing a node application that serves client-side JavaScript code to a static webpage. The goal is to have the code evaluated within the webpage, similar to the concept demonstrated in this example, but using Node.js instead ...

Remove a Row from a Table by Clicking a Button with Ajax

I currently have an HTML table with 4 columns: SKU Group, Group_ID, Edit button, and Delete button. My focus at the moment is on implementing the delete functionality. I want it so that when the delete button is clicked, a confirmation box appears. If "OK" ...

Is it possible for a cloud function to safely carry out asynchronous tasks after it has fulfilled its promise?

Is it safe for a cloud function to execute async tasks after returning its promise? Take into consideration the following code pattern: exports.deleteUser = functions.auth.user().onDelete(async (user) => { const uid = user.uid; asyncTask1(uid); ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

Retrieve data from a variable that is located within a function that is also

<script> const tally ={ total: 0, increase: function(){ total++; console.log(total); } } const selectBtn = document.getElementsByTagName('button& ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

Changing the name of a specific attribute in a JSON Object for showcasing it in an HTML Table

Suppose I have fetched a list of objects from a database: [{ "id":0 ,"name":"John", "lastname":"Shell" },{ "id":1,...]; and want to display this data using the dynatable plugin: data : JSON.stringify(data) success: function(data,status){ $( ...

Animate.css does not function properly when loaded locally

I'm currently using a Flask server to host an HTML file for testing purposes. Within the head of this HTML file, I have linked to a locally stored animate.min.css file (<link rel="stylesheet" type="text/css" href="{{ url_fo ...

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

Issue with React component not displaying in the browser.Here are some

I am currently following a React tutorial on and I'm facing an issue where the Counter component is not displaying on the page. The generated HTML looks like this: <html> <head> <script src="/bundle.js" ></script> </he ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...