Counting how many seconds a user dragging the mouse - javascript

I have a function where the user sort of "scratching" a surface when he drags the mouse over it, reviling content underneath this surface. I want to count how many seconds he dragged the mouse, and when he reaches 5 seconds - do something. If he lets go after, for example, 3 seconds, the count should stop and resume from 3d second when he resumes dragging. I tried to do it with setInterval and add 1 to seconds counter every 1000 ms, but no matter what I've tried - I'm either getting some crazy numbers in the counter or it just stays on 0. Here's my code:
var interval, info;
var totalSeconds = 0;
function init()
{
...more vars declaration and initialization
function scratchOff(x, y)
{
mainctx.save();
mainctx.beginPath();
mainctx.arc(x,y,radius,0,Math.PI*2,false);
mainctx.clip();
mainctx.drawImage(bottomImage, 0, 0);
mainctx.restore();
}
$('#overlay').mousedown(function(e){
isMouseDown = true;
var relX = e.pageX;
var relY = e.pageY;
scratchOff(relX, relY, true);
});
$('#overlay').mousemove(function(e){
var relX = e.pageX;
var relY = e.pageY;
overlayctx.clearRect(0,0,canvasWidth,canvasHeight);
overlayctx.drawImage(coinImage, relX-radius, relY-radius);
if (isMouseDown) {
scratchOff(relX, relY, false);
countSeconds(); // - THIS CALLS FOR THE FUNCTION THAT IS SUPPOSED
// TO COUNT SECONDS ONCE THE USER STARTS DRAGGING THE MOUSE
}
});
$('#overlay').mouseup(function(e){
isMouseDown = false;
clearInterval(interval);
});
var mainctx = $('canvas')[0].getContext('2d');
var radius = 10;
topImage.onload = function(){
mainctx.drawImage(topImage, 0, 0);
};
topImage.src = "images/oie_canvas.png";
}
// THIS IS THE FUNCTION THAT'S SUPPOSED TO COUNT SECONDS
function countSeconds() {
interval = setInterval(function(){
totalSeconds = totalSeconds++;
info.innerHTML = totalSeconds;
if(totalSeconds >= 5) clearInterval(interval);
}, 1000);
}
How can I make it work?

You would start a timer of 1 sec, which monitor your isMouseDown flag and start counting, when you reach 5 sec you go for your action, no need to call the countSeconds every time.
Here is an example:
EDITED
$(function() {
setInterval(function(){
if(isMouseDown) {
totalSeconds++;
}
if(totalSeconds== 5) {
//do your action;
totalSeconds = 0;
}
info.innerHTML = totalSeconds;
}, 1000);
} );
var isMouseDown = false;
function init()
{
... your code
}
EDITED 2
Full Example
var topImage = new Image();
var bottomImage = new Image();
var coinImage = new Image();
bottomImage.src = "http://i58.tinypic.com/2i093ia.jpg";
coinImage.src = "http://i61.tinypic.com/30acmtt.png";
var info;
var interval;
var totalSeconds = 0;
$(function() {
setInterval(function(){
if(isMouseDown) {
totalSeconds++;
}
if(totalSeconds== 5) {
alert("5 sec");
totalSeconds = 0;
}
info.innerHTML = totalSeconds;
}, 1000);
} );
var isMouseDown = false;
function init()
{
var canvasWidth = $('#myCanvas').width();
var canvasHeight = $('#myCanvas').height();
$('body').append('<canvas id="overlay" width="'+canvasWidth+'" height="'+canvasHeight+'" />');
var overlayctx = $('canvas')[1].getContext('2d');
overlayctx.drawImage(coinImage, 0,0);
info = document.getElementById('info');
function scratchOff(x, y)
{
mainctx.save();
mainctx.beginPath();
mainctx.arc(x,y,radius,0,Math.PI*2,false);
mainctx.clip();
mainctx.drawImage(bottomImage, 0, 0);
mainctx.restore();
}
$('#overlay').mousedown(function(e){
isMouseDown = true;
var relX = e.pageX;
var relY = e.pageY;
scratchOff(relX, relY, true);
});
$('#overlay').mousemove(function(e){
var relX = e.pageX;
var relY = e.pageY;
overlayctx.clearRect(0,0,canvasWidth,canvasHeight);
overlayctx.drawImage(coinImage, relX-radius, relY-radius);
if (isMouseDown) {
scratchOff(relX, relY, false);
countSeconds();
}
});
$('#overlay').mouseup(function(e){
isMouseDown = false;
clearInterval(interval);
});
var mainctx = $('canvas')[0].getContext('2d');
var radius = 10;
topImage.onload = function(){
mainctx.drawImage(topImage, 0, 0);
};
topImage.src = "http://i61.tinypic.com/xpzbx0.png";
}

Related

Prevent double images in function using Math.random

I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};

How do I use a repeat function to reset everything and run everything over again?

I have a repeat function which runs on a button on-click event, however it's not working properly. Maybe because there are too many setIntervals running although I tried to clear them all. I also made sure to reset the variables used back to their initial values, however the moving circle keeps showing up faded when the shoot again button is pressed, so I'm assuming there's an issue with the setInterval, however, I don't know what it is.It's also not drawing the basketball again.
var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;
var ctx = canvas.getContext("2d");
var intervalId2;
var intervalId1;
//Initializing Variables
var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;
var resetVars = function() {
dt = 0.01;
var x = r + 1;
var y = 500 / 1.2;
var xc = 145;
var yc = 300;
var dxc = 95;
var dyc = 300;
var theta = 0;
};
//resetVars();
var reset = function() {
ctx.clearRect(0, 0, 800, 800);
drawHoop()
};
//Interval Id to eventually clear it to stop this to shoot
var intervalID = setInterval(moveCirc, 10000 * dt);
var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
var repeat = function() {
reset();
clearInterval(intervalID);
clearInterval(intervalId2);
clearInterval(intervalId1);
resetVars();
drawBasketball();
drawHoop();
moveCirc();
intervalID = setInterval(moveCirc, 10000 * dt);
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>
<body style="background-color:powderblue;">
<p id="count"></p>
<button id="again" onclick="repeat()"> Shoot Again </button>
</body>
This should make a stop button for a repeating function
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
Stop

Javascript canvas "game". Hero mooves only one time

Im trying to make simple game in canvas. I made animation for hero using setTimeout() function. I check pressed keys with function moove(e):
Everything works pretty fine when i press leftarrow or rightarrow for the first time, but then hero doesnt moove. Any recomendations to the code is appreciated.
var cns = document.getElementById("can");
cns.height = 600;
cns.width = 300;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "images/hero.png";
hero.onload = function() {
ctx.drawImage(hero, 120, 570);
hero.xx = 120;
hero.yy = 570;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function moove(e) {
keys[e.keyCode] = (e.type == "keydown");
if (keys[37]) {
clearTimeout(intervalR);
clearTimeout(intervalRR);
goLeft(hero);
} else {
clearTimeout(intervalL);
clearTimeout(intervalLL);
}
if (keys[39]) {
clearTimeout(intervalL);
clearTimeout(intervalLL);
goRight(hero);
} else {
clearTimeout(intervalR);
clearTimeout(intervalRR);
}
}
function goLeft(img) {
var x = img.xx,
y = img.yy;
function f() {
ctx.clearRect(img.xx, img.yy, img.width, img.height);
ctx.drawImage(img, x, y);
img.xx = x;
img.yy = y;
x -= 1.2;
if (x < -35) {
x = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
Function goRight is similiar to goLeft.
Function moove is called in tag body onkeydown='moove(event)' onkeyup='moove(event)'.
You can check the project here: https://github.com/Fabulotus/Fabu/tree/master/Canvas%20game%20-%20dodge%20and%20jump
The reason it doesn't work the first time is because the first time through you are setting the position to its previous position (x = image.xx) then updating x after you draw. You should update the x value x -= 1.2 before calling drawImage
Here is a "working" version of your code:
var cns = document.getElementById("can");
cns.height = 170;
cns.width = 600;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "http://swagger-net-test.azurewebsites.net/api/Image";
hero.onload = function() {
ctx.drawImage(hero, cns.width-10, cns.height/2);
hero.xx = cns.width-10;
hero.yy = cns.height/2;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function goLeft(img) {
function f() {
ctx.beginPath()
ctx.clearRect(0, 0, cns.width, cns.height);
ctx.drawImage(img, img.xx, img.yy);
img.xx--;
if (img.xx < -img.width) {
img.xx = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
goLeft(hero)
<canvas id="can">
As you can see the function goLeft has been significantly simplified.
One recommendation: avoid the many setTimeout and clearTimeout instead use one setInterval to call a draw function that takes care of drawing everything on your game, all the other function should just update the position of your gameObjects.

How to remove a tween with createjs

I have a clock hand that rotates as a timer. If the user completed activity before the time runs out I need to stop that tween.
I tried remove tween with no luck. What am I doing wrong?
I get into my levelup function but the remove tween does not work.
function Clock() {
// this.board = board;
clockContainer = new createjs.Container();
contain = new createjs.Container();
var clockBack = new createjs.Bitmap(queue.getResult("clockBack"));
clockHand = new createjs.Bitmap(queue.getResult("clockHand"));
clockBack.x = 40;
clockBack.y = 480;
clockHand.x = 95;
clockHand.y = 539;
clockHand.regX = 20
clockHand.regY = 105;
clockHand.scaleX = clockHand.scaleY = 0.50;
clockBack.scaleX = clockBack.scaleY = 0.50;
clockContainer.addChild(clockBack, clockHand);
TimerLength = 30000;
stage.addChild(clockContainer)
mytweentodisable = createjs.Tween.get(clockHand, { loop: false }).to({ rotation: 360 }, TimerLength).call(function () {
//this will trigger the timer is up
GamehasEnded = true;
checkWrongAndRight();
});
}
function levelUp() {
createjs.Tween.removeTweens(mytweentodisable)
console.log("adding Level up button");
levelUpContainer = new createjs.Container();
levelUpIcon = new createjs.Bitmap(queue.getResult("levelUp"));
levelUpContainer.addChild(levelUpIcon);
stage.addChild(levelUpContainer)
levelUpContainer.x = 350
levelUpContainer.y = 500
levelUpContainer.addEventListener("click", function () {
console.log("clicked it");
});
}
This should do the trick:
mytweentodisable.setPaused(true);

Can't move an object using setInterval function

I want to make a rectangular move by click on a button and stop it clicking on the same button. Here is a part of my code:
document.getElementById("startStop").addEventListener("click", changePlace);
function changePlace() {
nIntervMove = setInterval(movement, 100);
};
var tmp1 = 0;
function movement() {
var oElem = document.getElementById("colorRectangular");
oElem.getPropertyValue = tmp1;
tmp1 += "10px";
};
function stopMove(){
clearInterval(nIntervMove);
};
Pretty straight forward:
var makeMove = function(x, hx, t, complete) {
var target = document.getElementById('rect'),
dx = 0,
d = setInterval(function() {
target.style.left = dx + "px";
dx += hx;
if(dx >= x) {
clearInterval(d);
complete();
}
}, t);
};
makeMove(100, 5, 500, function() {
alert('done');
});
JSFiddle: http://jsfiddle.net/8ay9cqmd/

Categories