Mouse Proximity to object Javascript - javascript

I'm struggling with this for a while now. I'm drawing a grid on the canvas. I add a mousemove eventHandler and track the mouseX and mouseY positions. I would like to be able to calculate the distance from the mouse position to the item in the grid. I can't seem to get this right, I've tried a few different solutions, like adding a loop in the mousemove handler and using requestAnimationFrame, but both solutions are very slow.
Here's my code below:
function setupCanvas(){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
blockWidth = width/2 - 150;
blockHeight = height/2 - 100;
gridArray = [];
gridWidthArray = [];
ctx.fillRect(0,0,width,height);
//drawGrid();
drawInitGrid();
canvas.addEventListener('mousemove',onMouseMoveHandler);
}
function drawInitGrid(){
for(x = 0; x<16; x++){
for(y = 0; y<11; y++){
var gridBlock = new GridBlock((blockWidth) + x*20, (blockHeight) + y*20, blockWidth, blockHeight);
gridBlock.render(ctx);
gridArray.push(gridBlock);
//gridWidthArray.push(gridBlock.xPos)
}
}
}
function onMouseMoveHandler(e){
if(containerBounds(e)){
mouseX = e.offsetX;
mouseY = e.offsetY;
console.log(mouseX, mouseY);
//console.log(gridWidthArray);
for(var grid in gridArray){
//console.log(gridArray[grid].xPos)
}
}
}
I've also tried adding a mouseevent in the GridBlock object, but that also doesn't seem to work.

You can calculate the distance between any 2 points like this:
var dx=point2.x-point1.x;
var dy=point2.y-point1.y;
var distance=Math.sqrt(dx*dx+dy*dy);
Also in your fiddle your mouse position calculation should account for the offset position of the canvas within the window:
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
function onMouseMoveHandler(e){
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
}
[ Finding nearest point in grid ]
Assume you have a mouse position [mx,my] and assume you have a grid with its top-left at [0,0] and with its cell size at cellWidth X cellHeight.
Then you can calculate the grid cell closest to the mouse like this:
var cellX=parseInt((mx+cellWidth/2)/cellWidth)*cellWidth;
var cellY=parseInt((my+cellHeight/2)/cellHeight)*cellHeight;
Of course, if the grid's top-left is not at [0,0], you will have to adjust for the gridss offset.

Related

How to move a canvas element on top of another canvas element

I have 2 canvas elements on top of each other and i want to move the canvas element on top on mouse drag but it produces weird results.
This is my code for the events (the variable cvs is the canvas element which is on top of other canvas element)
var drag = false;
cvs.addEventListener('mousedown', function(event) {
drag = true;
});
cvs.addEventListener('mouseup', function(event) {
drag = false;
});
cvs.addEventListener('mousemove', function(event) {
if (drag) {
const rect = cvs.getBoundingClientRect()
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
cvs.style.left = x + "px";
cvs.style.top = y + "px";
console.log(x, y);
}
});
When I drag the top canvas it starts to flicker back-and-forth between 2 positions
At a glance, it looks like you are using a relative value to set an absolute position.
So, first iteration, the left position updates to x, then the next iteration you subtract the last value of x from the mouse position. I think this is going to move it on and off screen.
say, clientX is at 100, and left is at 10.
T1 -> x = 100 - 10 = 90,
T2 -> x = 100 - 90 = 10.
Hence the "flickering"
What you want to do, is take the relative movement value of the mouse and move the element by the same amount.
So on mouse down, record the mouse initial position and element initial position.
Subtract the initial mouse position from the mouse position on each mouse move iteration, and assign the initial element position plus the relative change to the element.
var initialPosition = null
var initialMouseCoords = null
cvs.addEventListener('mousedown', function(event) {
initialPosition = cvs.getBoundingClientRect()
initialMouseCoords = {clientX: event.clientX, clientY: event.clientY}
});
cvs.addEventListener('mouseup', function(event) {
initialPosition = null
initialMouseCoords = null
});
cvs.addEventListener('mousemove', function(event) {
if (initialMouseCoords) {
const dx = event.clientX - initialMouseCoords.clientX;
const dy = event.clientY - initialMouseCoords.clientY;
cvs.style.left = initialPosition.left + dx;
cvs.style.top = initialPosition.top + dy;
console.log(dx, dy);
}
});
Bare in mind there are drag events depending on your use case, you might want to explore that as an alternative.

getting proper mouse position inside a zoomable iframe

I have a project on svg-edit where i have to create polygon on mouse-click , the svg-canvas (not HTML5 canvas suppose as drawing board) is zoomable, i can create polygon on 100% zoom but when i zoomin or zoomout i can't, actually i am unable to get right x and y position after zoom.as you can see in image.
I had tried this method to get points--
//Container 1440*1920
var svgcanvas = document.getElementById("svgcanvas");
//zoom
var initialZoom = 1440 * 1920;
zoomWidth = parseFloat(svgcanvas.style.width);
zoomHeight = parseFloat(svgcanvas.style.height);
currentZoom = zoomHeight * zoomWidth;
zoom = currentZoom / initialZoom;
//points
var rect = event.target.getBoundingClientRect();
var x1 = ((event.clientX) / zoom) - rect.left;
var y1 = ((eevent.clientY) / zoom) - rect.top;
and my task is
It seems you are not interacting with the svg-edit API at all. Things get much easier if you do.
// do not interact with the DOM element, but with the API object
var svgcanvas = svgEditor.canvas;
// your event listener function
function listener (event) {
var rect = svgcanvas.getBBox(event.target);
var x1 = rect.x;
var y = rect.y;
...
}
No need to handle zooming; the SvgCanvas instance does that for you.

Smoothly predicting the location of the mouse cursor in javascript

I want to draw a rectangle on a canvas around the mouse cursor that smoothly follows the cursor. Unfortunately, the mousemoved event doesn't fire quickly enough, and the drawing constantly trails behind it. So I'm assuming I need to predict where the mouse is, and draw the rectangle at that point. I'm trying to write a simple library to abstract that away, but it's not tracking as closely as I'd like for fast movements (in fact, fast movements are jittery). For slow movements, it tracks fairly well, and better than the simple solution of using the raw mouse coordinates.
The basic idea is that mousemove updates a couple of external variables with the current position of the mouse. A requestAnimationFrame loop (the Watcher function) tracks these variables and their previous values over time to calculate the speed the mouse is moving at (in the x axis). When the PredictX function is called, it returns the current x position, plus the last change in x multiplied by the speed. A different reqeustAnimationFrame loop moves the rectangle based on the predicted x value.
var MouseLerp = (function () {
var MOUSELERP = {};
var current_x = 0;
var last_x = 0;
var dX = 0;
var last_time = 0;
var x_speed = 0;
var FPS = 60;
function Watcher(time) {
var dT = time - last_time
if (dT > (1000 / FPS)) {
dX = last_x - current_x;
last_x = current_x;
x_speed = dX / dT
last_time = time;
}
requestAnimationFrame(Watcher);
}
MOUSELERP.PredictX = function () {
return Math.floor((dX * x_speed) + current_x);
}
MOUSELERP.Test = function () {
var target_element = $(".container")
target_element.append('<canvas width="500" height="500" id="basecanvas"></canvas>');
var base_ctx = document.getElementById("basecanvas").getContext("2d");
var offset = target_element.offset()
var offset_x = offset.left;
var offset_y = offset.top;
var WIDTH = $(window).width();
var HEIGHT = $(window).height();
var FPS = 60;
var t1 = 0;
function updateRect(time) {
var dT = time - t1
if (dT > (1000 / FPS)) {
base_ctx.clearRect(0, 0, WIDTH, HEIGHT)
base_ctx.beginPath();
base_ctx.strokeStyle = "#FF0000";
base_ctx.lineWidth = 2;
base_ctx.rect(MOUSELERP.PredictX(), 100, 100, 100)
base_ctx.stroke();
t1 = time;
}
requestAnimationFrame(updateRect)
}
updateRect();
$(target_element).mousemove(function (event) {
current_x = event.pageX - offset_x;
});
requestAnimationFrame(Watcher);
}
MOUSELERP.Test()
return MOUSELERP;
}())
What am I doing wrong?
Here's a jsfiddle of the above: http://jsfiddle.net/p8Lr224p/
Thanks!
The mouse pointer will always be quicker than drawing, so your best bet is not to give the user's eye a reason to perceive latency. So, turn off the mouse cursor while the user is drawing. Draw a rectangle at the mouse position to visually act as the mouse cursor.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var mouseX=0;
var mouseY=0;
canvas.style.cursor="none";
$("#canvas").mousemove(function(e){handleMouseMove(e);});
function handleMouseMove(e){
ctx.clearRect(mouseX-1,mouseY-1,9,9);
mouseX=e.clientX-offsetX;
mouseY=e.clientY-offsetY;
ctx.fillRect(mouseX,mouseY,8,8);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Less 'lagging' when mouse is invisible & canvas draws cursor.</h4>
<canvas id="canvas" width=300 height=300></canvas>
,

Obtain co-ordinates of an HTML5 canvas on a page

I have a a canvas inside another canvas.
<canvas id ='canvas2' height="718" width="1316"></canvas>
its css is something
#canvas2{
position:absolute;
width :95%;
height:90%;
top:5%;
left:2.5%;
background: #ffff56;
cursor:pointer;
}
next I have drawn some rectangles on it. I need to colour those with mouse click. I used an action listener.
var canvas = document.getElementById("canvas2");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", doMouseDown, false);
var $canvas = $("#canvas2");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
function doMouseDown(event){
event.preventDefault();
event.stopPropagation();
var x= parseInt(event.clientX - offsetX);
var y = parseInt(event.clientY - offsetY);
}
But this is not the right way I know as I am getting all the wrong canvas co-ordinates on x and y.
Can someone show the right way?
Has your canvas been scrolled?
If yes, then you also need to account for the distance the canvas has been scrolled in the browser.
You might check out canvas.getBoundingClientRect() as a way to get the canvas position with the scrolling accounted for:
function handleMousemove(e){
e.preventDefault();
e.stopPropagation();
// if the canvas is stationary (not scrolling) then you can do
// .getBoundingClientRect once at the start of the app
var BB=canvas.getBoundingClientRect();
// calc mouse position based on the bounding box
var mouseX=parseInt(e.clientX-BB.left);
var mouseY=parseInt(e.clientY-BB.top);
console.log(mouseX+"/"+mouseY);
}

HTML5 canvas rectangles using easeljs

I am creating a multiple choice quiz on a canvas.
Naturally for the options I used squares as checkBoxes. Now I have put an event Listener on clicking a checkbox, it should get colored. However the listener doesnt work on entire square only the border. May I know how can the problem be resolved and also I wanted to know how to know if a square is filled with a color.
Function for loading options with oIndex from 0,1, till numberOfOptions
pHeight is a a global variable, optionChecks- the checkbox and optionsClick- the invisible rectangle for clicking on
function loadOption(oIndex){
optionChecks[oIndex] = new createjs.Shape();
optionChecks[oIndex].graphics.beginStroke("blue");
optionChecks[oIndex].graphics.setStrokeStyle(2);
optionChecks[oIndex].graphics.drawRect( canvas2.width*0.05 ,pHeight+20 ,20 ,20);
stage.addChild(optionChecks[oIndex] );
stage.update();
var y1 = pHeight+15;
var ht = y1;
var maxWidth = canvas2.width *0.8;
var text = problemOptions[oIndex];
var lineHeight = 25;
var x = (canvas2.width - maxWidth) / 2;
var y = y1;//pHeight+15;
//function for wrapping text
wrapText(ctx2, text, x, y, maxWidth, lineHeight);
ht = wHeight +10;
stage.update();
optionClicks[oIndex] = new createjs.Shape();
optionClicks[oIndex].graphics.beginStroke("black");
optionClicks[oIndex].graphics.setStrokeStyle(2);
optionClicks[oIndex].graphics.drawRect( canvas2.width*0.05,y1,maxWidth-500 ,pHeight-y1+10);
optionClicks[oIndex].addEventListener("click", handleOption);
stage.addChild(optionClicks[oIndex] );
}
Thanks in advance.
You could draw another opaque rect and use the button's hitArea - http://createjs.com/Docs/EaselJS/classes/DisplayObject.html#property_hitArea

Categories