How to correctly kill off and reinitialize ScrollTrigger? (Nuxt + LocomotiveScroll) - javascript

I'm using GSAP ScrollTrigger and LocomotiveScroll in a Nuxt application. Everything is working fine so far, except when changing routes.
I guess, I have to kill off and reinitialize LocomotiveScroll and ScrollTrigger?
The relevant JS:
export default {
data() {
return {
lmS: null
};
},
mounted() {
this.lmS = new this.locomotiveScroll({
el: document.querySelector(".js-scroll"),
smooth: true,
direction: "horizontal",
lerp: 0.1,
smartphone: {
smooth: false,
direction: "vertical"
}
});
//////////////////SCROLLTRIGGER SETUP//////////////////
this.lmS.on("scroll", this.$ScrollTrigger.update);
var that = this;
this.$ScrollTrigger.scrollerProxy(".js-scroll", {
scrollTop(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.y;
},
scrollLeft(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.x;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
};
},
pinType: document.querySelector(".js-scroll").style.transform
? "transform"
: "fixed"
});
this.$ScrollTrigger.addEventListener("refresh", () => this.lmS.update());
this.$ScrollTrigger.refresh(true);
},
destroyed() {
//window.removeEventListener("refresh", () => this.lmS.update());
//let triggers = this.$ScrollTrigger.getAll();
//triggers.forEach((trigger) => {
//trigger.kill(false, true);
//});
this.lmS.destroy();
this.lmS = null;
}
};
I’ve set up a minimal codesandbox:
https://codesandbox.io/s/scrolltrigger-routechange-gv75r?file=/mixins/locomotive.js
Would appreciate any tips! :)
Updated JS:
export default {
data() {
return {
sTrigger: null
lmS: null
};
},
mounted() {
this.lmS = new this.locomotiveScroll({
el: document.querySelector(".js-scroll"),
smooth: true,
direction: "horizontal",
lerp: 0.1,
smartphone: {
smooth: false,
direction: "vertical"
}
});
//////////////////SCROLLTRIGGER SETUP//////////////////
this.sTrigger = this.$ScrollTrigger
this.lmS.on("scroll", this.sTrigger.update);
var that = this;
this.sTrigger.scrollerProxy(".js-scroll", {
scrollTop(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.y;
},
scrollLeft(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.x;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
};
},
pinType: document.querySelector(".js-scroll").style.transform
? "transform"
: "fixed"
});
this.sTrigger.addEventListener("refresh", () => this.lmS.update());
this.sTrigger.refresh(true);
},
beforeDestroy(){
window.removeEventListener('refresh', () => this.lmS.update())
let triggers = this.sTrigger.getAll()
triggers.forEach(trigger => {
trigger.kill()
})
this.sTrigger = null
},
destroyed() {
this.lmS.destroy();
this.lmS = null;
}
};

Related

How do you apply Smart Routing on links with ports on JointJS?

I am trying to apply smart routing of links with the use of ports using JointJS. This documentation shows the one I am trying to achieve. The example on the docs though shows only the programmatic way of adding Link from point A to point B. How do you do this with the use of ports?
Here's my code: JSFiddle.
HTML:
<html>
<body>
<button id="btnAdd">Add Table</button>
<div id="dbLookupCanvas"></div>
</body>
</html>
JS
$(document).ready(function() {
$('#btnAdd').on('click', function() {
AddTable();
});
InitializeCanvas();
// Adding of two sample tables on first load
AddTable(50, 50);
AddTable(250, 50);
});
var graph;
var paper
var selectedElement;
var namespace;
function InitializeCanvas() {
let canvasContainer = $('#dbLookupCanvas').parent();
namespace = joint.shapes;
graph = new joint.dia.Graph({}, {
cellNamespace: namespace
});
paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
}
});
//Dragging navigation on canvas
var dragStartPosition;
paper.on('blank:pointerdown',
function(event, x, y) {
dragStartPosition = {
x: x,
y: y
};
}
);
paper.on('cell:pointerup blank:pointerup', function(cellView, x, y) {
dragStartPosition = null;
});
$("#dbLookupCanvas")
.mousemove(function(event) {
if (dragStartPosition)
paper.translate(
event.offsetX - dragStartPosition.x,
event.offsetY - dragStartPosition.y);
});
// Remove links not connected to anything
paper.model.on('batch:stop', function() {
var links = paper.model.getLinks();
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
if (source.id === undefined || target.id === undefined) {
link.remove();
}
});
});
paper.on('cell:pointerdown', function(elementView) {
resetAll(this);
let isElement = elementView.model.isElement();
if (isElement) {
var currentElement = elementView.model;
currentElement.attr('body/stroke', 'orange');
selectedElement = elementView.model;
} else
selectedElement = null;
});
paper.on('blank:pointerdown', function(elementView) {
resetAll(this);
});
$('#dbLookupCanvas')
.attr('tabindex', 0)
.on('mouseover', function() {
this.focus();
})
.on('keydown', function(e) {
if (e.keyCode == 46)
if (selectedElement) selectedElement.remove();
});
}
function AddTable(xCoord = undefined, yCoord = undefined) {
// This is a sample database data here
let data = [
{columnName: "radomData1"},
{columnName: "radomData2"}
];
if (xCoord == undefined && yCoord == undefined)
{
xCoord = 50;
yCoord = 50;
}
const rect = new joint.shapes.standard.Rectangle({
position: {
x: xCoord,
y: yCoord
},
size: {
width: 150,
height: 200
},
ports: {
groups: {
'a': {},
'b': {}
}
}
});
$.each(data, (i, v) => {
const port = {
group: 'a',
args: {}, // Extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: {
y: 6
} // Extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: [{
tagName: 'text',
selector: 'label'
}]
},
attrs: {
body: {
magnet: true,
width: 16,
height: 16,
x: -8,
y: -4,
stroke: 'red',
fill: 'gray'
},
label: {
text: v.columnName,
fill: 'black'
}
},
markup: [{
tagName: 'rect',
selector: 'body'
}]
};
rect.addPort(port);
});
rect.resize(150, data.length * 40);
graph.addCell(rect);
}
function resetAll(paper) {
paper.drawBackground({
color: 'white'
});
var elements = paper.model.getElements();
for (var i = 0, ii = elements.length; i < ii; i++) {
var currentElement = elements[i];
currentElement.attr('body/stroke', 'black');
}
var links = paper.model.getLinks();
for (var j = 0, jj = links.length; j < jj; j++) {
var currentLink = links[j];
currentLink.attr('line/stroke', 'black');
currentLink.label(0, {
attrs: {
body: {
stroke: 'black'
}
}
});
}
}
Any help would be appreciated. Thanks!
The default link created when you draw a link from a port is joint.dia.Link.
To change this you can use the defaultLink paper option, and configure the router you would like.
defaultLink documentation reference
const paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
},
defaultLink: () => new joint.shapes.standard.Link({
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
});
You could also provide several default options in the paper.
defaultLink: () => new joint.shapes.standard.Link(),
defaultRouter: { name: 'manhattan' },
defaultConnector: { name: 'rounded' }

Camera not following spaceship

I'm a newb, when it comes to developing games, especially with a new language and framework. I'm having trouble at making the camera stick to the player. Not sure where should I put the this.camera.startFollow(); statement so it would work. The game is an asteroids remake, however, the map is larger than 800x600. The game is already set up with socket.io. Here's the code:
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 3200,
height: 2400,
physics: {
default: 'arcade',
arcade: {
debug: false,
gravity: {
x: 0,
y: 0
}
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
const game = new Phaser.Game(config);
function preload() {
this.load.image('ship', 'assets/spaceShips_001.png');
this.load.image('otherPlayer', 'assets/enemyBlack5.png');
this.load.image('star', 'assets/star_gold.png');
this.load.image('backgroundStar1', 'assets/star2.png');
this.load.image('backgroundStar2', 'assets/star3.png');
this.load.image('space', 'assets/deep-space.jpg');
//this.load.image('background', 'assets/background.png');
}
function create() {
var self = this;
this.add.tileSprite(0, 0, 6400, 4800, 'space');
this.physics.world.setBounds(0, 0, 3200, 3200);
//this.cameras.main.setBounds(0, 0, 3200, 3200);
this.socket = io();
this.otherPlayers = this.physics.add.group();
this.socket.on('currentPlayers', function (players) {
Object.keys(players).forEach(function (id) {
if (players[id].playerId === self.socket.id) {
addPlayer(self, players[id]);
//this.camera.startFollow(self.ship); - does not work
} else {
addOtherPlayers(self, players[id]);
}
});
});
this.socket.on('newPlayer', function (playerInfo) {
addOtherPlayers(self, playerInfo);
});
this.socket.on('disconnect', function (playerId) {
self.otherPlayers.getChildren().forEach(function (otherPlayer) {
if (playerId === otherPlayer.playerId) {
otherPlayer.destroy();
}
});
});
this.socket.on('playerMoved', function (playerInfo) {
self.otherPlayers.getChildren().forEach(function (otherPlayer) {
if (playerInfo.playerId === otherPlayer.playerId) {
otherPlayer.setRotation(playerInfo.rotation);
otherPlayer.setPosition(playerInfo.x, playerInfo.y);
}
});
});
this.cursors = this.input.keyboard.createCursorKeys();
this.blueScoreText = this.add.text(16, 16, '', { fontSize: '32px', fill: '#0000FF' });
this.redScoreText = this.add.text(584, 16, '', { fontSize: '32px', fill: '#FF0000' });
this.socket.on('scoreUpdate', function (scores) {
self.blueScoreText.setText('Blue: ' + scores.blue);
self.redScoreText.setText('Red: ' + scores.red);
});
this.socket.on('starLocation', function (starLocation) {
if (self.star) self.star.destroy();
self.star = self.physics.add.image(starLocation.x, starLocation.y, 'star');
self.physics.add.overlap(self.ship, self.star, function () {
this.socket.emit('starCollected');
}, null, self);
});
}
function addPlayer(self, playerInfo) {
self.ship = self.physics.add.image(playerInfo.x, playerInfo.y, 'ship').setOrigin(0.5, 0.5).setDisplaySize(53, 40).setCollideWorldBounds(true);
if (playerInfo.team === 'blue') {
self.ship.setTint(0x0000ff);
} else {
self.ship.setTint(0xff0000);
}
self.ship.setDrag(100);
self.ship.setAngularDrag(100);
self.ship.setMaxVelocity(200);
}
function addOtherPlayers(self, playerInfo) {
const otherPlayer = self.add.sprite(playerInfo.x, playerInfo.y, 'otherPlayer').setOrigin(0.5, 0.5).setDisplaySize(53, 40);
if (playerInfo.team === 'blue') {
otherPlayer.setTint(0x0000ff);
} else {
otherPlayer.setTint(0xff0000);
}
otherPlayer.playerId = playerInfo.playerId;
self.otherPlayers.add(otherPlayer);
}
function update() {
if (this.ship) {
if (this.cursors.left.isDown) {
this.ship.setAngularVelocity(-150);
} else if (this.cursors.right.isDown) {
this.ship.setAngularVelocity(150);
} else {
this.ship.setAngularVelocity(0);
}
if (this.cursors.up.isDown) {
this.physics.velocityFromRotation(this.ship.rotation + 1.5, 100, this.ship.body.acceleration);
} else {
this.ship.setAcceleration(0);
}
this.physics.world.wrap(this.ship, 5);
// emit player movement
var x = this.ship.x;
var y = this.ship.y;
var r = this.ship.rotation;
if (this.ship.oldPosition && (x !== this.ship.oldPosition.x || y !== this.ship.oldPosition.y || r !== this.ship.oldPosition.rotation)) {
this.socket.emit('playerMovement', { x: this.ship.x, y: this.ship.y, rotation: this.ship.rotation });
}
// save old position data
this.ship.oldPosition = {
x: this.ship.x,
y: this.ship.y,
rotation: this.ship.rotation
};
}
}
Solved by adding the following code in the create() function:
window.scene = this;
then changed my commented line
//this.cameras.main.setBounds(0, 0, 3200, 3200);
to
scene.cameras.main.setBounds(0, 0, 3200, 3200);
and lastly added
scene.cameras.main.startFollow(self.ship);
in my addPlayer() function.

Muuri multiple grid data

How i can draw data-id for each column item in my function updateIndices simillar to updateColumnIndices?
I want to make my grid more dynamic.
I using only javascript and Muuri lib for drag and drop.
Thank you for help.
Muuri is a JavaScript layout engine that allows you to build all kinds of layouts and make them responsive, sortable, filterable, draggable and/or animated. Comparing to what's out there Muuri is a combination of Packery, Masonry, Isotope and Sortable. Wanna see it in action? Check out the demo on the website.
My code for this task under spoiler
function setupItemContainer() {
let itemContentContainer = document.querySelectorAll('.board-column-content');
for(let i = 0; i < itemContentContainer.length; i++)
{
if(!itemContentContainer[i].classList.contains('muuri'))
{
itemContainers.push(itemContentContainer[i]);
muuriItems = new Muuri(itemContentContainer[i], {
itemDraggingClass: 'muuri-item-default-dragging',
dragSortHeuristics: {
sortInterval: 10,
minDragDistance: 5,
minBounceBackAngle: Math.PI / 2
},
dragPlaceholder: {
enabled: true,
duration: 100,
easing: 'ease',
createElement: null,
onCreate: null,
onRemove: null
},
items: '.board-item',
layoutDuration: 400,
layoutEasing: 'ease',
dragEnabled: true,
dragSort: function () {
return columnGrids;
},
dragSortInterval: 0,
dragContainer: document.body,
dragReleaseDuration: 400,
dragReleaseEasing: 'ease',
itemPlaceholderClass: 'muuri-item-placeholder'
})
.on('dragStart', function (item) {
item.getElement().style.width = item.getWidth() + 'px';
item.getElement().style.height = item.getHeight() + 'px';
})
.on('dragReleaseEnd', function (item) {
item.getElement().style.width = '';
item.getElement().style.height = '';
columnGrids.forEach(function (muuriItems) {
muuriItems.refreshItems();
});
})
.on('layoutStart', function () {
muuriColumns.refreshItems().layout();
})
.on('move', updateIndices)
.on('sort', updateIndices);
columnGrids.push(muuriItems);
}
}
}
function setupColumnsContainer() {
muuriColumns = new Muuri(gridElement, {
itemDraggingClass: 'muuri-item-column-dragging',
layoutDuration: 400,
layoutEasing: 'ease',
dragEnabled: true,
dragSortInterval: 0,
dragStartPredicate: {
handle: '.board-column-header'
},
dragReleaseDuration: 400,
dragReleaseEasing: 'ease',
})
.on('move', updateColumnIndices)
.on('sort', updateColumnIndices);
}
function updateColumnIndices() {
muuriColumns.getItems().forEach(function (item, i) {
item.getElement().setAttribute('data-id', i);
});
}
function updateIndices() {
muuriItems.getItems().forEach(function (item, i) {
item.getElement().setAttribute('data-id', i);
});
}

React pose - animate in from right, exit on left

I am currently playing around with React pose. What I'm trying to do is animate different boxes in from the right, and exit them on the left. However, I can't seem to get the preEnterPose to work the way I want it. It always seems to default to the exit pose.
How can I get the boxes to animate in from the right, and exit on the left? Here is what I am working with
https://codesandbox.io/s/react-pose-enterexit-o2qqi?fontsize=14&hidenavigation=1&theme=dark
import React from "react";
import ReactDOM from "react-dom";
import posed, { PoseGroup } from "react-pose";
import "./styles.css";
const Card = posed.div({
enter: {
x: 0,
opacity: 1,
preEnterPose: {
x: 50
},
delay: 300,
transition: {
x: { type: "spring", stiffness: 1000, damping: 15 },
default: { duration: 300 }
}
},
exit: {
x: -50,
opacity: 0,
transition: { duration: 150 }
}
});
class Example extends React.Component {
state = { isVisible: false, index: 0, items: ["1", "2", "3", "4", "5"] };
componentDidMount() {}
next = () => {
if (this.state.index === this.state.items.length - 1) {
this.setState({
index: 0
});
} else {
this.setState({
index: this.state.index + 1
});
}
};
render() {
const { index, items } = this.state;
return (
<div>
<PoseGroup>
{items.map((id, idx) => {
if (idx === index) {
return (
<Card className="card" key={idx}>
{id}
</Card>
);
}
return null;
})}
</PoseGroup>
<button onClick={this.next}>next</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);
First you update your posed.div as the following.
const Card = posed.div({
preEnterPose: {
x: 50,
opacity: 0,
transition: { duration: 150 }
},
enter: {
x: 0,
opacity: 1,
delay: 300,
transition: {
x: { type: "spring", stiffness: 1000, damping: 15 },
default: { duration: 300 }
}
},
exit: {
x: -50,
opacity: 0,
transition: { duration: 150 }
}
});
Then you set your <PoseGroup>'s preEnterPose props to your key of the pose preEnterPose. And it should work. preEnterPose's default props is set to exit. Read it here
<PoseGroup preEnterPose="preEnterPose">
{items.map((id, idx) => {
if (idx === index) {
return (
<Card className="card" key={idx}>
{id}
</Card>
);
}
return null;
})}
</PoseGroup>

PHP - Show Mobile Camera to Capture QR Code

I want to show the camera of my mobile on the form. but what i have for now is the camera is showing ONLY on web page of the Desktop not on the web page of the Mobile, why? why i cant access the camera of my mobile? please help thanks here is the code of the webcam.js
var WebCodeCamJS = function(element) {
'use strict';
this.Version = {
name: 'WebCodeCamJS',
version: '2.7.0',
author: 'Tóth András',
};
var mediaDevices = window.navigator.mediaDevices;
mediaDevices.getUserMedia = function(c) {
return new Promise(function(y, n) {
(window.navigator.getUserMedia || window.navigator.mozGetUserMedia || window.navigator.webkitGetUserMedia).call(navigator, c, y, n);
});
}
HTMLVideoElement.prototype.streamSrc = ('srcObject' in HTMLVideoElement.prototype) ? function(stream) {
this.srcObject = !!stream ? stream : null;
} : function(stream) {
if (!!stream) {
this.src = (window.URL || window.webkitURL).createObjectURL(stream);
} else {
this.removeAttribute('src');
}
};
var videoSelect, lastImageSrc, con, beepSound, w, h, lastCode;
var display = Q(element),
DecodeWorker = null,
video = html('<video muted autoplay playsinline></video>'),
sucessLocalDecode = false,
localImage = false,
flipMode = [1, 3, 6, 8],
isStreaming = false,
delayBool = false,
initialized = false,
localStream = null,
options = {
decodeQRCodeRate: 5,
decodeBarCodeRate: 3,
successTimeout: 500,
codeRepetition: true,
tryVertical: true,
frameRate: 15,
width: 320,
height: 240,
constraints: {
video: {
mandatory: {
maxWidth: 1280,
maxHeight: 720
},
optional: [{
sourceId: true
}]
},
audio: false,
},
flipVertical: false,
flipHorizontal: false,
zoom: 0,
beep: 'audio/beep.mp3',
decoderWorker: 'js/DecoderWorker.js',
brightness: 0,
autoBrightnessValue: 0,
grayScale: 0,
contrast: 0,
threshold: 0,
sharpness: [],
resultFunction: function(res) {
console.log(res.format + ": " + res.code);
},
cameraSuccess: function(stream) {
console.log('cameraSuccess');
},
canPlayFunction: function() {
console.log('canPlayFunction');
},
getDevicesError: function(error) {
console.log(error);
},
getUserMediaError: function(error) {
console.log(error);
},
cameraError: function(error) {
console.log(error);
}
};
and here is my code of the Play which will trigger the button to show the camera
function play() {
if (!localImage) {
if (!localStream) {
init();
}
const p = video.play();
if (p && (typeof Promise !== 'undefined') && (p instanceof Promise)) {
p.catch(e => null);
}
delay();
}
}

Categories

Resources