JS radio player keeps resetting while navigating the website - javascript

I am using a JS radio player on a website. Anytime someone goes to a new page or refreshes the current page the volume slider resets to 25%. Also, Every time someone goes to a new page the radio player restarts itself causing a break in the music. What would be the best way to fix these issues so that it remembers the users volume and the music doesn't break upon switching pages? I currently have the initial volume set to 25% on load up because it is extremely loud for some reason.
--EDIT--
My question about volume has been answered, now I just need a solution for keeping the player from restarting while switching pages.
Radio Player JS:
'use strict';
var audioPlayer = document.querySelector('.ggr-radio-player');
var playPause = audioPlayer.querySelector('#playPause');
var playpauseBtn = audioPlayer.querySelector('.play-pause-btn');
var loading = audioPlayer.querySelector('.loading');
var progress = audioPlayer.querySelector('.ggr-progress');
var sliders = audioPlayer.querySelectorAll('.ggr-slider');
var volumeBtn = audioPlayer.querySelector('.ggr-volume-btn');
var volumeControls = audioPlayer.querySelector('.ggr-volume-controls');
var volumeProgress = volumeControls.querySelector('.ggr-slider .ggr-progress');
var player = audioPlayer.querySelector('audio');
var currentTime = audioPlayer.querySelector('.current-time');
var totalTime = audioPlayer.querySelector('.total-time');
var speaker = audioPlayer.querySelector('#speaker');
var draggableClasses = ['pin'];
var currentlyDragged = null;
player.volume = 0.25;
window.addEventListener('mousedown', function (event) {
if (!isDraggable(event.target)) return false;
currentlyDragged = event.target;
var handleMethod = currentlyDragged.dataset.method;
this.addEventListener('mousemove', window[handleMethod], false);
window.addEventListener('mouseup', function () {
currentlyDragged = false;
window.removeEventListener('mousemove', window[handleMethod], false);
}, false);
});
playpauseBtn.addEventListener('click', togglePlay);
player.addEventListener('timeupdate', updateProgress);
player.addEventListener('volumechange', updateVolume);
player.addEventListener('loadedmetadata', function () {
totalTime.textContent = formatTime(player.duration);
});
player.addEventListener('canplay', makePlay);
player.addEventListener('ended', function () {
playPause.attributes.d.value = "M18 12L0 24V0";
player.currentTime = 0;
});
volumeBtn.addEventListener('click', function () {
volumeBtn.classList.toggle('open');
volumeControls.classList.toggle('hidden');
});
window.addEventListener('resize', directionAware);
sliders.forEach(function (slider) {
var pin = slider.querySelector('.pin');
slider.addEventListener('click', window[pin.dataset.method]);
});
directionAware();
function isDraggable(el) {
var canDrag = false;
var classes = Array.from(el.classList);
draggableClasses.forEach(function (draggable) {
if (classes.indexOf(draggable) !== -1) canDrag = true;
});
return canDrag;
}
function inRange(event) {
var rangeBox = getRangeBox(event);
var rect = rangeBox.getBoundingClientRect();
var direction = rangeBox.dataset.direction;
if (direction == 'horizontal') {
var min = rangeBox.offsetLeft;
var max = min + rangeBox.offsetWidth;
if (event.clientX < min || event.clientX > max) return false;
}
else {
var min = rect.top;
var max = min + rangeBox.offsetHeight;
if (event.clientY < min || event.clientY > max) return false;
}
return true;
}
function updateProgress() {
var current = player.currentTime;
var percent = current / player.duration * 100;
progress.style.width = percent + '%';
currentTime.textContent = formatTime(current);
}
function updateVolume() {
volumeProgress.style.height = player.volume * 100 + '%';
if (player.volume >= 0.5) {
speaker.attributes.d.value = 'M14.667 0v2.747c3.853 1.146 6.666 4.72 6.666 8.946 0 4.227-2.813 7.787-6.666 8.934v2.76C20 22.173 24 17.4 24 11.693 24 5.987 20 1.213 14.667 0zM18 11.693c0-2.36-1.333-4.386-3.333-5.373v10.707c2-.947 3.333-2.987 3.333-5.334zm-18-4v8h5.333L12 22.36V1.027L5.333 7.693H0z';
}
else if (player.volume < 0.5 && player.volume > 0.05) {
speaker.attributes.d.value = 'M0 7.667v8h5.333L12 22.333V1L5.333 7.667M17.333 11.373C17.333 9.013 16 6.987 14 6v10.707c2-.947 3.333-2.987 3.333-5.334z';
}
else if (player.volume <= 0.05) {
speaker.attributes.d.value = 'M0 7.667v8h5.333L12 22.333V1L5.333 7.667';
}
}
function getRangeBox(event) {
var rangeBox = event.target;
var el = currentlyDragged;
if (event.type == 'click' && isDraggable(event.target)) {
rangeBox = event.target.parentElement.parentElement;
}
if (event.type == 'mousemove') {
rangeBox = el.parentElement.parentElement;
}
return rangeBox;
}
function getCoefficient(event) {
var slider = getRangeBox(event);
var rect = slider.getBoundingClientRect();
var K = 0;
if (slider.dataset.direction == 'horizontal') {
var offsetX = event.clientX - slider.offsetLeft;
var width = slider.clientWidth;
K = offsetX / width;
}
else if (slider.dataset.direction == 'vertical') {
var height = slider.clientHeight;
var offsetY = event.clientY - rect.top;
K = 1 - offsetY / height;
}
return K;
}
function changeVolume(event) {
if (inRange(event)) {
player.volume = getCoefficient(event);
}
}
function formatTime(time) {
var min = Math.floor(time / 60);
var sec = Math.floor(time % 60);
return min + ':' + (sec < 10 ? '0' + sec : sec);
}
function togglePlay() {
if (player.paused) {
playPause.attributes.d.value = "M0 0h6v24H0zM12 0h6v24h-6z";
player.play();
}
else {
playPause.attributes.d.value = "M18 12L0 24V0";
player.pause();
}
}
function makePlay() {
playpauseBtn.style.display = 'block';
loading.style.display = 'none';
}
function directionAware() {
if (window.innerHeight < 250) {
volumeControls.style.bottom = '-54px';
volumeControls.style.left = '54px';
}
else if (audioPlayer.offsetTop < 154) {
volumeControls.style.bottom = '-164px';
volumeControls.style.left = '-3px';
}
else {
volumeControls.style.bottom = '52px';
volumeControls.style.left = '-3px';
}
}
Radio Player HTML:
<div class="ggr-radio">
<div class="ggr-now-playing">
<marquee behavior="scroll" direction="left" scrollamount="2">
<span id="cc_strinfo_trackartist_gamersguildradio" class="cc_streaminfo"></span> - <span id="cc_strinfo_tracktitle_gamersguildradio" class="cc_streaminfo"></span>
</marquee>
</div>
<div class="audio ggr-radio-player">
<div class="loading">
<div class="spinner"></div>
</div>
<div class="play-pause-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="24" viewBox="0 0 18 24">
<path fill="#566574" fill-rule="evenodd" d="M0 0h6v24H0zM12 0h6v24h-6z" class="play-pause-icon" id="playPause" />
</svg>
</div>
<div class="controls">
<span class="current-time">0:00</span>
</div>
<div class="ggr-volume">
<div class="ggr-volume-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path fill="#566574" fill-rule="evenodd" d="M14.667 0v2.747c3.853 1.146 6.666 4.72 6.666 8.946 0 4.227-2.813 7.787-6.666 8.934v2.76C20 22.173 24 17.4 24 11.693 24 5.987 20 1.213 14.667 0zM18 11.693c0-2.36-1.333-4.386-3.333-5.373v10.707c2-.947 3.333-2.987 3.333-5.334zm-18-4v8h5.333L12 22.36V1.027L5.333 7.693H0z" id="speaker"/>
</svg>
</div>
<div class="ggr-volume-controls hidden">
<div class="ggr-slider" data-direction="vertical">
<div class="ggr-progress">
<div class="pin" id="ggr-volume-pin" data-method="changeVolume">
</div>
</div>
</div>
</div>
</div>
<audio crossorigin autoplay id="radio">
<source src="http://192.95.18.39:5272/stream" type="audio/mp3">
</audio>
</div>
</div>

When the page is loading you setting the slider value everytime: player.volume = 0.25;
When the user changes the slider value or leave the current page, store the value it in a cookie.
When the page is refreshed, load the stored values from your cookie to the player.

Related

Progress bar not updating even with SetTimeout

I have this inside index.html
<body>
<script>
window.onload=function() {
let videoDiv = createVideoDiv()
document.getElementById("contentVideo").appendChild(videoDiv);
document.addEventListener("keydown", function(inEvent){
controlVideo(inEvent.keyCode);
});
}
</script>
<div id="progressBarWrapper">
<div id="progressBar"></div>
</div>
<div id="contentVideo"></div>
</body>
and this css
#progressBarWrapper {
width: 100%;
height:15px;
background-color: black;
}
#progressBar {
width: 0%;
height: 15px;
background-color: green;
}
this is how the video div is created:
function createVideoDiv() {
var video = document.createElement("VIDEO");
video.setAttribute('controls', '');
//video.setAttribute('autoplay', '');
video.setAttribute('preload', 'auto');
video.setAttribute('width', larguraVideo);
video.setAttribute('id', 'video');
var source = document.createElement("SOURCE");
source.setAttribute('src', obterVideoClicado());
source.setAttribute('type', 'video/mp4');
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
});
video.addEventListener('loadeddata', function() {
var myBar = document.getElementById("progressBarWrapper");
myBar.style = "display:none;";
video.play();
});
video.appendChild(source);
return video;
}
this is how the progress bar is adjusted
function ajustarProgressBar(valor) {
var progressBar = document.getElementById("progressBar");
progressBar.style.width = valor + "%";
}
Even the progress bar is being fired by
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
the progress bar is not updating and stays 0% all the time.
The progress bar is to be adjusted by the video download progress.
The video progress is working fine. I have printed that to console and the values are changing as the video download progresses.
You have to pass param to function:
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
--Edit
Your video progress event listener would now look like:
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
});
The setTimeout function takes 2 parameters:
The function to call after the delay time
The delay time in milliseconds
So to call your function you must make a function that will call your function like this:
setTimeout(() => ajustarProgresBar(loadPercentage * 100), 40);
So in your code it might look like this:
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(() => ajustarProgressBar(loadPercentage*100), 40);

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

Transforming img - white dots appear on chronium

I am trying to get 3d transform effect of the bacground image on mouse move.
I have checked f.e. jquery.plate tilt.js and many others plugins, BUT, each of them has problem on chronium browsers like Chrome or Opera (it works fine even on IE11 -.-)
See the attachment and please adwise what is that and if it is fixable? The "dots" appear on mouse move (when background moves) randomly but in line within image.
(function($) {
'use strict';
var namespace = 'jquery-plate';
function Plate($element, options) {
this.config(options);
this.$container = $element;
if (this.options.element) {
if (typeof this.options.element === 'string') {
this.$element = this.$container.find(this.options.element);
} else {
this.$element = $(this.options.element);
}
} else {
this.$element = $element;
}
this.originalTransform = this.$element.css('transform');
this.$container
.on('mouseenter.' + namespace, this.onMouseEnter.bind(this))
.on('mouseleave.' + namespace, this.onMouseLeave.bind(this))
.on('mousemove.' + namespace, this.onMouseMove.bind(this));
}
Plate.prototype.config = function(options) {
this.options = $.extend({
inverse: false,
perspective: 500,
maxRotation: 10,
animationDuration: 200
}, this.options, options);
};
Plate.prototype.destroy = function() {
this.$element.css('transform', this.originalTransform);
this.$container.off('.' + namespace);
};
Plate.prototype.update = function(offsetX, offsetY, duration) {
var rotateX;
var rotateY;
if (offsetX || offsetX === 0) {
var height = this.$container.outerHeight();
var py = (offsetY - height / 2) / (height / 2);
rotateX = this.round(this.options.maxRotation * -py);
} else {
rotateY = 0;
}
if (offsetY || offsetY === 0) {
var width = this.$container.outerWidth();
var px = (offsetX - width / 2) / (width / 2);
rotateY = this.round(this.options.maxRotation * px);
} else {
rotateX = 0;
}
if (this.options.inverse) {
rotateX *= -1;
rotateY *= -1;
}
if (duration) {
this.animate(rotateX, rotateY, duration);
} else if (this.animation && this.animation.remaining) {
this.animation.targetX = rotateX;
this.animation.targetY = rotateY;
} else {
this.transform(rotateX, rotateY);
}
};
Plate.prototype.reset = function(duration) {
this.update(null, null, duration);
};
Plate.prototype.transform = function(rotateX, rotateY) {
this.currentX = rotateX;
this.currentY = rotateY;
this.$element.css('transform',
(this.originalTransform && this.originalTransform !== 'none' ? this.originalTransform + ' ' : '') +
'perspective(' + this.options.perspective + 'px) ' +
'rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)'
);
};
Plate.prototype.animate = function(rotateX, rotateY, duration) {
if (duration) {
this.animation = this.animation || {};
var remaining = this.animation.remaining;
this.animation.time = performance.now();
this.animation.remaining = duration || null;
this.animation.targetX = rotateX;
this.animation.targetY = rotateY;
if (!remaining) {
requestAnimationFrame(this.onAnimationFrame.bind(this));
}
} else {
this.transform(rotateX, rotateY);
}
};
Plate.prototype.round = function(number) {
return Math.round(number * 1000) / 1000;
};
Plate.prototype.offsetCoords = function(event) {
var offset = this.$container.offset();
return {
x: event.pageX - offset.left,
y: event.pageY - offset.top
};
};
Plate.prototype.onAnimationFrame = function(timestamp) {
this.animation = this.animation || {};
var delta = timestamp - (this.animation.time || 0);
this.animation.time = timestamp;
var duration = this.animation.remaining || 0;
var percent = Math.min(delta / duration, 1);
var currentX = this.currentX || 0;
var currentY = this.currentY || 0;
var targetX = this.animation.targetX || 0;
var targetY = this.animation.targetY || 0;
var rotateX = this.round(currentX + (targetX - currentX) * percent);
var rotateY = this.round(currentY + (targetY - currentY) * percent);
this.transform(rotateX, rotateY);
var remaining = duration - delta;
this.animation.remaining = remaining > 0 ? remaining : null;
if (remaining > 0) {
requestAnimationFrame(this.onAnimationFrame.bind(this));
}
};
Plate.prototype.onMouseEnter = function(event) {
var offset = this.offsetCoords(event);
this.update(offset.x, offset.y, this.options.animationDuration);
};
Plate.prototype.onMouseLeave = function(event) {
this.reset(this.options.animationDuration);
};
Plate.prototype.onMouseMove = function(event) {
var offset = this.offsetCoords(event);
this.update(offset.x, offset.y);
};
$.fn.plate = function(options) {
return this.each(function() {
var $element = $(this);
var plate = $element.data(namespace);
if (options === 'remove') {
plate.destroy();
$element.data(namespace, null);
} else {
if (!plate) {
plate = new Plate($element, options);
$element.data(namespace, plate);
plate.reset();
} else {
plate.config(options);
}
}
});
};
})(jQuery);
$('#ab12cd').plate()
<div id="ab12cd" styles="width:100%;height:100%">
<img src="http://eskipaper.com/images/dark-background-8.jpg" />
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
// please open in new window, most visible effect you cen see if you move mouse bottom left/right

HTML5 Javascript game

I'm trying to make a HTML5 game in javascript. Similar to pong, but once the bubble hits the paddle or bottom screen it "bursts" or disappears. I cant seem to get the Bubble to disappear or burst in my code. Could anyone help me?
var canvasColor;
var x,y,radius,color;
var x=50, y=30
var bubbles=[];
var counter;
var lastBubble=0;
var steps=0, burst=0, escaped=0;
var batonMovement = 200;
var moveBatonRight = false;
var moveBatonLeft = false;
function startGame()
{
var r,g,b;
var canvas,color;
//Initialize
canvasColor = '#EAEDDC';
x = 10;
y = 10;
radius = 10;
clearScreen();
counter=0;
while (counter <100)
{
//make bubble appear randomly
x=Math.floor(Math.random()*450)
//Set up a random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
color='rgb('+r+','+g+','+b+')';
bubbles[counter] = new Bubble(x,y,radius,color);
counter+=1;
}
setInterval('drawForever()',50);
}
function Bubble (x,y,radius,color)
{
this.x=x;
this.y=y;
this.radius=radius;
this.color=color;
this.active=false;
}
function drawForever()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps +=1
clearScreen();
if (steps%20==0 && lastBubble < 100){
bubbles[lastBubble].active=true;
lastBubble +=1;
}
drawBaton();
counter=0;
while (counter <100)
{
if (bubbles[counter].active==true){
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2*Math.PI);
pen.fill();
bubbles[counter].y+=2;
}
if (y>=240 && y<=270 && x>=batonMovement-10 && x<=batonMovement+60)
{
bubbles[lastBubble]=false;
}
else if (y>=450)
{
bubbles[lastBubble]=false;
}
counter +=1;
}
}
function clearScreen()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = canvasColor;
pen.fillRect(0,0,450,300);
}
function drawBaton()
{
var canvas, pen;
if (moveBatonLeft == true && batonMovement > 0)
{
batonMovement -= 20;
}
else if (moveBatonRight == true && batonMovement < 400)
{
batonMovement += 20;
}
//draw Baton (rectangle)
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = '#0000FF';
pen.fillRect(batonMovement,250,50,10);
}
function moveLeft()
{
moveBatonLeft=true;
}
function moveRight()
{
moveBatonRight=true;
}
function stopMove()
{
moveBatonLeft=false;
moveBatonRight=false;
}
Below is the HTML code...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bubble Burster</title>
<script type="text/javascript" src="project.js"></script>
</head>
<body onload="startGame();">
<div style="text-align:center;">
<h2>Bubble Burster</h2>
<canvas id="myCanvas" width="450" height="300" style="border:5px solid #000000; background-color: #f1f1f1;">
Your browser does not support the canvas element.
</canvas><br>
<button onmousedown="moveLeft();" onmouseup="stopMove();">LEFT</button>
<button onmousedown="moveRight();" onmouseup="stopMove();">RIGHT</button><br><br>
<form>
<input type="radio" name="difficulty" value="easy" onclick="check(this.value);" checked> Easy
<input type="radio" name="difficulty" value="moderate" onclick="check(this.value)"> Moderate
<input type="radio" name="difficulty" value="hard" onclick="check(this.value)"> Hard <br><br>
</form>
<span id="burst">Burst:</span>
<span id="escaped">Escaped: </span>
<span id="steps">Steps elapsed:</span>
<h3 id="output"></h3>
</div>
</body>
</html>
You are referring to x, y which are not defined in the drawForever function. The global values of x and y may not refer to the right bubble. In fact y is set to 10 in the startGame function and never altered subsequently. You also probably want to refer to bubbles[counter] rather than bubbles[lastBubble]. The game seems to work if you make the changes below, referring to bubbles[counter].x and bubbles[counter].y instead of x and y.
function drawForever() {
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps += 1
clearScreen();
if (steps % 20 == 0 && lastBubble < 100) {
bubbles[lastBubble].active = true;
lastBubble += 1;
}
drawBaton();
counter = 0;
while (counter < 100) {
if (bubbles[counter].active == true) {
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2 * Math.PI);
pen.fill();
bubbles[counter].y += 2;
}
y = bubbles[counter].y; // ADDED (y was not defined in original code)
x = bubbles[counter].x; // ADDED (x was not defined in original code)
if (y >= 240 && y <= 270 && x >= batonMovement - 10 && x <= batonMovement + 60) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
} else if (y >= 450) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
}
counter += 1;
}
}
https://jsfiddle.net/acLot87q/4/
You should also make x and y local variables within each function; they are not currently serving the purpose that you seem to think.

Pure Javascript How to Zoom Image on mousemove?

I'm trying to create onmousemove event inside the image then show the zoomed image in the right side.
Problem:
When I try to mousemove inside the image, the black box and zoomed image are blinking.
The zoomed image is not match in the blackbox.
How do I do that? May computation is wrong.
This is my code.
<div>
<div id="cursor" style="background:black; opacity:0.5; width:100px; height:100px; position:absolute; display:none">
</div>
<div style="float:left;">
<img id="img" src="http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg" onmousemove="getPos(event)" onmouseout="stopTracking()"/>
</div>
<div id="zoom" style="width:300px; height:300px; zoom:1; float:left;">
qwe
</div>
</div>
<script>
function getPos(e){
var x = e.clientX;
var y = e.clientY;
var width = document.getElementById("img").clientWidth;
var height = document.getElementById("img").clientHeight;
document.getElementById("cursor").style.left = x - 50;
document.getElementById("cursor").style.top = y - 50;
document.getElementById("cursor").style.display = "inline-block";
document.getElementById("zoom").style.background = "url('http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg') "+x / width * 100+"% "+y / width * 100+"%";
}
function stopTracking(){
document.getElementById("cursor").style.display = "none";
document.getElementById("zoom").style.background = "transparent";
}
</script>
I added time delay of half a second, the blinking is gone.
function getPos(e){
var delay=500; //1/2 second
setTimeout(function() {
//your code to be executed after 1/2 second
var x = e.clientX;
var y = e.clientY;
var width = document.getElementById("img").clientWidth;
var height = document.getElementById("img").clientHeight;
document.getElementById("cursor").style.left = x - 50;
document.getElementById("cursor").style.top = y - 50;
document.getElementById("cursor").style.display = "inline-block";
document.getElementById("zoom").style.background = "url('http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg') "+x / width * 100+"% "+y / width * 100+"%";
}, delay);
}
catch source from my e-commerce project (i'm using GSAP library for animation u can create custom CSS class with transitions instead):
<div class="grid col-10 rel z300">
<div class="border padt20 padb20 padl20 padr20 zoom--in flex align-center">
<img class="auto" src="img/prod.jpg" data-zoom="img/prod-large.jpg" alt="">
</div>
</div>
export class zoom_in_gallery {
constructor() {
if (!this.setVars()) return;
this.setEvents();
}
setVars() {
let _this = this;
_this.zoom = document.body.getElementsByTagName('section')[0].getElementsByClassName('zoom--in')[0];
if (!this.zoom) return false;
_this.img = this.zoom.firstElementChild;
if (!this.img) return false;
_this.zoom_pop = false;
_this.act = false;
return true;
}
setEvents() {
let _this = this;
function del(el) => {
el = typeof el === 'string' ? document.body.getElementsByClassName(el)[0] : el;
if (!el || !el.parentNode) return;
return el.parentNode.removeChild(el);
}
this.obj.onmove = (e) => {
if (_this.act) return;
let y = e.offsetY ? (e.offsetY) : e.pageY - _this.img.offsetTop,
x = e.offsetX ? (e.offsetX) : e.pageX - _this.img.offsetLeft;
if (!_this.zoom_pop) {
_this.zoom_pop = _this.render(e.target.parentNode, `<div class="top0 right0 abs o-hidden border" style="right:calc(-70%);left:initial;height:${_this.zoom.offsetWidth / 1.5}px;width:${_this.zoom.offsetWidth / 1.5}px"><div style="width:100%;height:100%;background: #fff url(${_this.img.dataset.zoom}) 0 0 / cover scroll no-repeat"></div></div>`);
TweenLite.fromTo(_this.zoom_pop, .3, {autoAlpha: 0}, {autoAlpha: 1});
}
_this.zoom_pop.firstElementChild.style.backgroundPosition = `${x / 3.8}% ${y / 3.8}%`;
};
this.obj.onleave = () => {
if (!_this.zoom_pop || _this.act) return;
_this.act = true;
TweenLite.to(_this.zoom_pop, .3, {
autoAlpha: 0, onComplete: () => {
del(_this.zoom_pop);
_this.zoom_pop = false;
_this.act = false;
}
});
};
this.zoom.addEventListener('mousemove', this.obj.onmove);
this.zoom.addEventListener('mouseout', this.obj.onleave);
}
render(relEl, tpl, cfg = {}) {
if (!relEl) return;
const parse = typeof cfg.parse === 'undefined' ? true : cfg.parse, child;
if (tpl.nodeName === 'TEMPLATE') {
child = document.importNode(tpl.content, true);
} else if (typeof tpl === 'string') {
const range = document.createRange();
range.selectNode(relEl);
child = range.createContextualFragment(tpl);
} else {
child = tpl;
}
if (parse) {
relEl.appendChild(child);
return relEl.lastElementChild;
}
return {rel: relEl, el: child};
}
}

Categories