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]
}
}