Camera not following spaceship - javascript

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.

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' }

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

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;
}
};

How to reuse assets in multiple scenes

I want to reuse assets in multiple scenes, but I get this error:
Texture key already in use
Here is the relevant code. Notice that I want to use the same spritesheet in both scenes. How do I do that without getting this error?
class InventoryScene extends Phaser.Scene {
constructor() {
super({ key: 'InventoryScene', active: true });
}
preload() {
this.load.spritesheet('sheet1', 'assets/sheet1.png',
{ frameWidth: 16, frameHeight: 16 });
}
create() {
this.add.sprite(this.game.canvas.width * .50,
this.game.canvas.height * .50, 'sheet1')
.setFrame(0)
.setInteractive()
.on('pointerdown', () => this.zoomIn())
.setScale(6);
}
}
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene', active: true });
}
preload() {
this.load.spritesheet('sheet1', 'assets/sheet1.png',
{ frameWidth: 16, frameHeight: 16 });
}
create() {
this.add.sprite(this.game.canvas.width * .50, this
.game.canvas.height * .50, 'sheet1')
.setFrame(0)
.setVisible(false);
}
}
Here is my game config:
var config = {
...
// Order here matters. The first scene is listed last.
scene: [DebugScene, InventoryScene, GameScene, HowToPlayScene, TitleScene]
};
Then I use this.scene.bringToTop('HowToPlayScene') to activate a scene.
PS: I am using Phaser 3
I created for you modified example with Phaser v3.17.
Copy Paste the code below and replace exist one in the page.
Click on 'Run Code' button on the top of the screen and may be have to wait 5-10 seconds:
https://labs.phaser.io/edit.html?src=src/scenes/changing%20scene.js
Scenes will be changed by click on first scene and others in loop.
Pay attention on "face" and "balls" spritesheet that was loaded only in first scene and this.scene.start('sceneB');
var SceneA = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function SceneA() {
Phaser.Scene.call(this, { key: 'sceneA' });
},
preload: function () {
this.load.image('face', 'assets/pics/bw-face.png');
this.load.spritesheet('balls', 'assets/sprites/balls.png', { frameWidth: 17, frameHeight: 17 });
},
create: function () {
this.add.sprite(400, 300, 'face').setAlpha(0.2);
this.add.sprite(400, 300, 'balls', 3);
this.input.once('pointerdown', function () {
console.log('From SceneA to SceneB');
this.scene.start('sceneB');
}, this);
}
});
var SceneB = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function SceneB() {
Phaser.Scene.call(this, { key: 'sceneB' });
},
preload: function () {
this.load.image('arrow', 'assets/sprites/longarrow.png');
},
create: function () {
this.add.sprite(400, 300, 'face').setAlpha(1);
this.arrow = this.add.sprite(400, 300, 'arrow').setOrigin(0, 0.5);
this.add.sprite(400, 300, 'balls', 3);
this.input.once('pointerdown', function (event) {
console.log('From SceneB to SceneC');
this.scene.start('sceneC');
}, this);
},
update: function (time, delta) {
this.arrow.rotation += 0.01;
}
});
var SceneC = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function SceneC() {
Phaser.Scene.call(this, { key: 'sceneC' });
},
preload: function () {
this.load.image('mech', 'assets/pics/titan-mech.png');
},
create: function () {
this.add.sprite(Phaser.Math.Between(0, 800), 300, 'mech');
this.add.sprite(400, 300, 'balls', 3);
this.input.once('pointerdown', function (event) {
console.log('From SceneC to SceneA');
this.scene.start('sceneA');
}, this);
}
});
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#000000',
parent: 'phaser-example',
scene: [SceneA, SceneB, SceneC]
};
var game = new Phaser.Game(config);

Control Scaling of Canvas When dragged out of chart limit

When I dragged the datapoint out of chart's ticks limit like from max x and y axis value, the canvas increase the limits too fast. How can I control this scaling speed? So that it increase with specific number defined in the config of chart.
Here is the js fiddle link.
https://jsfiddle.net/rz7pw6j0/67/
JS
(function () {
let chartInstance;
let chartElement;
function createChart(chartElement) {
const chartConfig = {
type: 'scatter',
data: {
datasets: [
{
data: [
{
x: 0,
y:0
}
],
fill: true,
showLine: true,
lineTension: 0
}
]
},
options: {
legend: {
display: false,
},
layout: {
padding: {
left: 50,
right: 50,
top: 0,
bottom: 0
}
},
title: {
display: false,
text: 'Chart.js Interactive Points',
},
scales: {
xAxes: [
{
type: 'linear',
display: true,
padding: 20,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
scaleLabel: {
display: true,
labelString: 'Time',
},
ticks: {
suggestedMin: -5,
suggestedMax: 5,
stepValue: 1,
}
}
],
yAxes: [
{
type: 'linear',
display: true,
scaleLabel: {
display: true,
labelString: 'Weight'
},
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
ticks: {
suggestedMin: 0,
suggestedMax: 3,
stepValue: 1
},
}
]
},
responsive: true,
maintainAspectRatio: true,
tooltips: {
intersect: true,
}
}
};
chartInstance = new Chart(chartElement.getContext('2d'), chartConfig);
let element = null;
let scaleY = null;
let scaleX = null;
let datasetIndex = null;
let index = null;
let valueY = null;
let valueX = null;
function onGetElement() {
const event = d3.event.sourceEvent;
element = chartInstance.getElementAtEvent(event)[0];
if (!element) {
chartClickHandler(event);
return;
}
if (event.shiftKey) {
const tempDatasetIndex = element['_datasetIndex'];
const tempIndex = element['_index'];
chartInstance.data.datasets[tempDatasetIndex].data = chartInstance
.data.datasets[tempDatasetIndex].data.filter((v, i) => i !== tempIndex);
chartInstance.update();
return;
}
scaleY = element['_yScale'].id;
scaleX = element['_xScale'].id;
}
function onDragStart() {
const event = d3.event.sourceEvent;
datasetIndex = element['_datasetIndex'];
index = element['_index'];
valueY = chartInstance.scales[scaleY].getValueForPixel(event.offsetY);
valueX = chartInstance.scales[scaleX].getValueForPixel(event.offsetX);
chartInstance.data.datasets[datasetIndex].data[index] = {
x: valueX,
y: valueY
};
chartInstance.update(0);
}
function onDragEnd() {
if (
chartInstance.data.datasets[datasetIndex] &&
chartInstance.data.datasets[datasetIndex].data) {
chartInstance.data.datasets[datasetIndex].data.sort((a, b) => a.x - b.x > 0 ? 1 : -1);
chartInstance.update(0);
}
element = null;
scaleY = null;
scaleX = null;
datasetIndex = null;
index = null;
valueY = null;
valueX = null;
}
d3.select(chartInstance.chart.canvas).call(
d3.drag().container(chartInstance.chart.canvas)
.on('start', onGetElement)
.on('drag', onDragStart)
.on('end', onDragEnd)
);
}
function chartClickHandler (event) {
let scaleRef;
let valueX = 0;
let valueY = 0;
Object.keys(chartInstance.scales).forEach((scaleKey) => {
scaleRef = chartInstance.scales[scaleKey];
if (scaleRef.isHorizontal() && scaleKey === 'x-axis-1') {
valueX = scaleRef.getValueForPixel(event.offsetX);
} else if (scaleKey === 'y-axis-1') {
valueY = scaleRef.getValueForPixel(event.offsetY);
}
});
const newPoint = {
x: valueX,
y: valueY
};
const dataSeries = chartInstance.data.datasets[0].data;
for (let i = 0; i < dataSeries.length; i++) {
if (dataSeries[i].x === newPoint.x) {
dataSeries.y = newPoint.y;
chartInstance.update();
return;
}
}
let inserted = false;
for (let j = dataSeries.length - 1; j >= 0; j--) {
if (dataSeries[j].x > newPoint.x) {
dataSeries[j + 1] = dataSeries[j];
} else {
dataSeries[j + 1] = newPoint;
inserted = true;
break;
}
}
if (!inserted) {
dataSeries.push(newPoint);
}
chartInstance.update();
}
chartElement = document.getElementById("chart");
createChart(chartElement);
})();
HTML
<body>
<div>Chart Drag and Click Test</div>
<div class="wrapper">
<canvas id="chart"></canvas>
</div>
</body>
CSS
.wrapper {
display: "block";
}
I want to control the scaling speed.
If a dragStart event occurs beyond the scale limits, the increment should be a fixed value to avoid the issue you mentioned. Also, ticks.min and ticks.max should be set for the same purpose. Below is a sample jsfiddle and code (you can control speed by step).
https://jsfiddle.net/oLrk3fb2/
function onDragStart() {
const event = d3.event.sourceEvent;
const scales = chartInstance.scales;
const scaleInstanceY = scales[scaleY];
const scaleInstanceX = scales[scaleX];
const scalesOpts = chartInstance.options.scales;
const ticksOptsX = scalesOpts.xAxes[0].ticks;
const ticksOptsY = scalesOpts.yAxes[0].ticks;
const step = 1;
datasetIndex = element['_datasetIndex'];
index = element['_index'];
valueY = scaleInstanceY.getValueForPixel(event.offsetY);
valueX = scaleInstanceX.getValueForPixel(event.offsetX);
if (valueY < scaleInstanceY.min) {
ticksOptsY.min = valueY = scaleInstanceY.min - step;
}
if (valueY > scaleInstanceY.max) {
ticksOptsY.max = valueY = scaleInstanceY.max + step;
}
if (valueX < scaleInstanceX.min) {
ticksOptsX.min = valueX = scaleInstanceX.min - step;
}
if (valueX > scaleInstanceX.max) {
ticksOptsX.max = valueX = scaleInstanceX.max + step;
}
chartInstance.data.datasets[datasetIndex].data[index] = {
x: valueX,
y: valueY
}
chartInstance.update(0);
}

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