How to trigger canvas drawing line animation without actual mouse move? - javascript

I am currently figuring out how to draw lines on page load without even having to actually moving the mouse to draw
Here is my code which draws line only when mouse is moved.
https://codepen.io/arvi/pen/RgYZqB
I added a "load" event listener and tied it to documentMouseMoveHandler but it seems not the solution for this scenario.
window.addEventListener('load', documentMouseMoveHandler, false);
Is it possible?

Ok do something like this until you get a mouse event , take random moue point in a interval if mouse event came, then remove it;
var intervalId;
function documentMouseMoveHandler(event) {
if (!event) {
intervalId = setInterval(function () {
mouseX = Math.floor(Math.random() * (window.innerWidth - 1));
mouseY = Math.floor(Math.random() * (window.innerHeight + 1));
}, 3000);
return;
}
if (event && intervalId) {
clearInterval(intervalId);
}
mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}`

Related

Make the following JavaScript modifications using clearInterval() and setInterval() where appropriate:

Make the following JavaScript modifications using clearInterval() and setInterval() where appropriate:
In startAnimation(), add an if statement that stops the timer with the ID timerId if timerId is not null.
After the if statement in startAnimation() that stops the timer, start a timer that calls moveImage(clickX, clickY) every 10 milliseconds. Save the timer ID in the timerId variable.
Add an if statement in moveImage() that stops the timer with the ID timerId if (imgX, imgY) is equal to (centerX, centerY). Also set timerId to null.
After the modifications are complete, the user should be able to click anywhere in the browser, and the heart will slowly move to the clicked location. If the user clicks on a new location before the heart arrives at the last location, the heart will adjust course and move to the new location.
Here is my code.
I keep get these errors in the photo even though I followed the instrutions
let timerId = null;
window.addEventListener("DOMContentLoaded", function() {
document.addEventListener("click", startAnimation);
});
function startAnimation(e) {
// Get mouse coordinates
let clickX = e.clientX;
let clickY = e.clientY;
// TODO: Modify the code below
if (timerId != null) {
clearInterval(timerId);
}
moveImage(clickX, clickY);
timerId = setInterval(moveImage, 10);
};
function moveImage(x, y) {
const img = document.querySelector("img");
// Determine location of image
let imgX = parseInt(img.style.left);
let imgY = parseInt(img.style.top);
// Determine (x,y) coordinates that center the image
// around the clicked (x, y) coords
const centerX = Math.round(x - (img.width / 2));
const centerY = Math.round(y - (img.height / 2));
// TODO: Add code here
if ((imgX, imgX == centerX) && (imgY == centerY)) {
clearInterval(timerId);
timerId = null;
}
// Move 1 pixel in both directions toward the click
if (imgX < centerX) {
imgX++;
}
else if (imgX > centerX) {
imgX--;
}
if (imgY < centerY) {
imgY++;
}
else if (imgY > centerY) {
imgY--;
}
img.style.left = imgX + "px";
img.style.top = imgY + "px";
};
I keep get these errors in the photo even though I followed the instructions
errors
The errors you're getting are basically saying that the code isn't working, which, if you run the code, you can see.
One handy way to see what's going on with your code is to use console.log and debugger
Note the difference between these two calls:
moveImage(clickX, clickY);
and
timerId = setInterval(moveImage, 10);
In each, you're making the call to moveImage, but in only one of them are you providing arguments for x and y.
We can remedy this by using a higher order function:
let timerId = null;
window.addEventListener("DOMContentLoaded", function() {
document.addEventListener("click", startAnimation);
});
function startAnimation(e) {
// Get mouse coordinates
let clickX = e.clientX;
let clickY = e.clientY;
// TODO: Modify the code below
if (timerId != null) {
clearInterval(timerId);
}
timerId = setInterval(moveImage(clickX, clickY), 10);
};
function moveImage(targetX, targetY) {
const img = document.querySelector("img");
return () => {
// Determine location of image
let imgX = parseInt(img.getBoundingClientRect().x);
let imgY = parseInt(img.getBoundingClientRect().y);
// Determine (x,y) coordinates that center the image
// around the clicked (x, y) coords
const centerX = Math.round(targetX - (img.width / 2));
const centerY = Math.round(targetY - (img.height / 2));
// TODO: Add code here
if ((imgX, imgX == centerX) && (imgY == centerY)) {
clearInterval(timerId);
timerId = null;
}
// Move 1 pixel in both directions toward the click
if (imgX < centerX) {
imgX++;
} else if (imgX > centerX) {
imgX--;
}
if (imgY < centerY) {
imgY++;
} else if (imgY > centerY) {
imgY--;
}
img.style.left = imgX + "px";
img.style.top = imgY + "px";
};
};
img {
position: fixed;
}
<img src="https://i.kym-cdn.com/photos/images/facebook/001/136/185/604.jpg" height="20" weidth="20" />
You can use getBoundingClientRect to find the position of the image, and once its position is set to fixed, changing the left and top properties will cause it to move.

How can I unbind an onClick event handler until it's needed?

I have an issue with a game in JavaScript.
My game lives inside a canvas, and I make large use of function almost like:
document.onmousemove = function(event) {
var mouseX = event.clientX - canvas.getBoundingClientRect().left;
var mouseY = event.clientY - canvas.getBoundingClientRect().top;
//mouse position is relative to player position
mouseX -= CANVAS_WIDTH/2;
mouseY -= CANVAS_HEIGHT/2;
player.aimAngle = Math.atan2(mouseY, mouseX) / Math.PI * 180;
}
document.onclick = function(event) {
if(player.canAttack && player.distance >= 80) { //not for sword attack
performAttack(player);
player.canAttack = false;
}
if(player.distance < 80)
performAttack(player);
event.preventDefault();
}
But before dynamically creating the canvas I have a login form. When I click with mouse to select those form I got in console the error Uncaught TypeError: Cannot read property 'canAttack' of undefined . That's because I have not called yet the Player() constructor, so canAttack doesn't exists and for the onMouseMove canvas doesn't exist yet.
How do I "disable" or unbind the document.onclick and document.onmousemove?
If they were done with addEventListener I would disable them with removeEventListener. How could I do with document.onclick instead?
Thanks
Try following when have to remove listener
function noop(){}
document.onclick = noop // when have to remove click binding

Bitmap move gradually to a click (easeljs)

I'd like my bitmap to go to a click position but I want to see a progression between the bitmap.x/bitmap.y and the click.x/click.y
How can I make this animation ?
Thanks a lot
You can create a tween using TweenJS when the stage is clicked:
stage.on("stagemousedown", function(event) {
// Tween to the new position. Override old tweens on the same object.
createjs.Tween.get(bitmapInstance, {override:true}).to({x:event.stageX, y:event.stageY}, 500, createjs.Ease.quadIn);
})
Here is a quick fiddle: http://jsfiddle.net/jemohtgh/
Or you can store the clicked position, and basically have the shape always try to reach that position (fiddle):
var pos = new createjs.Point();
stage.on("stagemousedown", function(event) {
pos.setValues(event.stageX, event.stageY);
})
function tick(event) {
// Move towards the position
s.x += (pos.x - s.x) / 2;
s.y += (pos.y - s.y) / 2;
stage.update(event);
}
You can also do the same thing with a mouse follow instead of a click (fiddle):
function tick(event) {
s.x += (stage.mouseX - s.x) / 5;
s.y += (stage.mouseY - s.y) / 5;
stage.update(event);
}
Cheers.

Applying transform with JavaScript on mousemove doesn't update on the fly

trying to make a div draggable, but only along the x-axis, the way a timestamp thumb on a video control can be dragged left and right to seek through a video or audio presentation.
Here's my code
thumb.addEventListener('mousemove', updateThumbPosition, false)
function updateThumbPosition (event) {
var thumbRect = thumb.getBoundingClientRect()
var startX = seekbar.getBoundingClientRect().left
var mouseX = event.clientX
console.log(mouseX - startX + thumbRect.width / 2)
thumb.style.transform = 'translateX(' + mouseX - startX + thumbRect.width / 2 + 'px)'
}
The div doesn't move. The values change rapidly as the mouse moves. I can see that when I log to the console, but the div itself does not translate along the X axis. Thoughts?
Here's a jsfiddle: https://jsfiddle.net/btjLqa8u/1/
You're only missing parentheses: https://jsfiddle.net/rjzLtunb/
div.style.transform = 'translateX(' + (mouseX - startX) + 'px)'
By the way, for drag and drop code, you probably want to listen for mouse moves on the div parent instead of the div itself.
I updated you fiddle with better mouse handling.
jsfiddle
s4mj3ch9
var div = document.getElementById('div')
div.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
function updateDivPosition (event) {
var divRect = div.getBoundingClientRect()
var startX = seekbar.getBoundingClientRect().left
var mouseX = event.clientX
div.style.transform = 'translateX(' + (mouseX - startX) + 'px)'
}
function mouseUp(){
window.removeEventListener('mousemove', updateDivPosition, true);
}
function mouseDown(){
window.addEventListener('mousemove', updateDivPosition, true);
}

Playing with Intervals in javascript

I have my object called player
var player = new Object();
player = {
x: (window.innerWidth / 2),
y: (window.innerHeight / 2),
width: 30,
height: 30,
color: 'red'
};
And some variable to check mouse down clicks
var mouseDown = 0;
And I have functions that is firing every 40ms...
function drawPlayer() {
var toPlayerX;
var toPlayerY;
var toPlayerLength;
toPlayerX = player.x - mouseX;
toPlayerY = player.y - mouseY;
toPlayerLength = Math.sqrt(toPlayerX * toPlayerX + toPlayerY * toPlayerY);
toPlayerX = toPlayerX / toPlayerLength;
toPlayerY = toPlayerY / toPlayerLength;
toPlayerLength = toPlayerLength - (toPlayerLength%1);
// this function get reduced distance between mouse and player canvas rect by 1px per click
function movePlayer() {
player.x -= toPlayerX;
player.y -= toPlayerY;
}
// on MOUSE DAWN EVENT
document.body.onmousedown = function() {
// on every mouse down click ++ mousedawn
++mouseDown;
// here we fire interval to make player alive and
// follow to mouse dawn click by ~25 pixels per secord
if (mouseDown==1) {
setInterval(movePlayer,40);
}
if (mouseDown>1) {
clearInterval(movePlayer());
mouseDown = 0;
}
};
}
The root of the problem is in this part
if (mouseDown>1) {
clearInterval(movePlayer());
mouseDown = 0;
}
I thought it will be clear movePlayer interval if mouseDown will have number of two, but instead the setInterval(movePlayer) just multiplie all the time while I click mouse, and making mouseDown = 0 works pretty well when it's go number of 2.
At the beginning I just wanna make code so when user clicks in some area the canvas player would follow straightly on area where the mouse was clicked and then stopped and while for example player is going somewhere already and the mouse was click again to change canvas first destination to area where the mouse was clicked last.
You have to set the setInterval command to a variable, and that is what you use to clear it.
So your code would look something like this:
// this function get reduced distance between mouse and player canvas rect by 1px per click
function movePlayer() {
player.x -= toPlayerX;
player.y -= toPlayerY;
}
var intervalID; // Declare the variable that is storing the interval.
// on MOUSE DAWN EVENT
document.body.onmousedown = function() {
// on every mouse down click ++ mousedawn
++mouseDown;
context.save();
context.fillStyle = 'black';
context.restore();
// here we fire interval to make player alive and follow to mouse dawn click by ~15 pixels per secord
if (mouseDown==1) {
intervalID = setInterval(movePlayer,40);
}
if (mouseDown>1) {
clearInterval(intervalID);
mouseDown = 0;
}
};
document.body.onmouseup = function() {
//--mouseDown;
};
clearInterval takes an intervalID returned from setInterval.
var timeoutId = 0;
if (mouseDown==1) {
timeoutId = setInterval(movePlayer,40);
}
if (mouseDown>1) {
clearInterval(timeoutId);
mouseDown = 0;
}
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval

Categories

Resources