HighCharts zoom with mouse wheel in react - reactjs

Intro
Hi I'm new to react and new to Highcharts but have worked with js before. I have a zoom function, I'd like to convert this to react code. I'm having hard time figuring out how to use Highcharts.Chart.prototype.callbacks.push in the context of react.
What I'm trying to do
I'm trying to create a zoom function that is smooth with the mouse wheel on a stock chart. The popular platform trading view has a very smooth zoom and I'm trying to do something similar to that.
The code:
I have the code working decently in a js fiddle https://jsfiddle.net/drewscatterday/84shran6/ but I'm having hard time converting this to react.
I have tried doing this in my react code but had no luck:
const handleScroll= (e) =>{
e.preventDefault();
var chart = Highcharts.chart;
var xAxis = chart.xAxis[0],
extremes = xAxis.getExtremes(),
newMin = extremes.min,
output = [];
if (e.deltaY < 0) {
xAxis.setExtremes(extremes.min - (extremes.min * 0.001), extremes.max, true);
}
else {
xAxis.setExtremes(extremes.min + (extremes.min * 0.001), extremes.max, true);
}
}
<div className="Chartdisplay__chart" id="chart" onScroll={handleScroll}>
<StockChart options={stockOptions} highcharts={Highcharts} />
</div>
I have also just tried adding the function straight up like this but also had no luck:
let ar = [];
(function(H) {
Highcharts.Chart.prototype.callbacks.push(function(chart) {
H.addEvent(chart.container, 'mousewheel', function(e) {
var xAxis = chart.xAxis[0],
extremes = xAxis.getExtremes();
if (e.deltaY < 0) {
xAxis.setExtremes(extremes.min - (extremes.min * 0.001), extremes.max, true);
}
else {
xAxis.setExtremes(extremes.min + (extremes.min * 0.001), extremes.max, true);
}
});
});
}(Highcharts));
Thank you for anyone who takes the time to read this and help me :)

To extend Higstock in React.js put the code that you want to wrap before the configuration object (options).
import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts/highstock'
import HighchartsReact from 'highcharts-react-official'
(function(H) {
Highcharts.Chart.prototype.callbacks.push(function(chart) {
H.addEvent(chart.container, 'wheel', function(e) {
var xAxis = chart.xAxis[0],
extremes = xAxis.getExtremes(),
newMin = extremes.min;
console.log(extremes);
console.log(newMin);
if (e.deltaY < 0) {
xAxis.setExtremes(extremes.min - (extremes.min * 0.001), extremes.max, true);
}
else {
xAxis.setExtremes(extremes.min + (extremes.min * 0.001), extremes.max, true);
}
});
});
}(Highcharts));
const options = {
title: {
text: 'My chart'
},
plotOptions: {
series: {
enableMouseTracking: true
}
}
https://www.highcharts.com/docs/extending-highcharts/extending-highcharts
Live demo: https://stackblitz.com/edit/react-hmvz2z?file=index.js

Related

Primeng table virtual scroll header jumping while scrolling up

I have a large set of data that needs virtual scrolling and I use PrimeNg v13.4.0 with angular/cdk v13.3.7. I have exactly the same issue with PrimeNg demo. When scrolling down, the sticky header works well, but when scrolling up, it start jumping, the faster scroll, the bigger jump. Does anyone has any solution for this?
This issue and its pull request is added to version 13 future milestone which has no due date.
https://github.com/primefaces/primeng/milestone/175
For now you can do this solution:
If you slow down the wheel speed of the cdk-virtual-scroll-viewport, even slightly,
The thead works as it should without any jumping.
changeWheelSpeed(container, speedY) {
var scrollY = 0;
var handleScrollReset = function() {
scrollY = container.scrollTop;
};
var handleMouseWheel = function(e) {
e.preventDefault();
scrollY += speedY * e.deltaY
if (scrollY < 0) {
scrollY = 0;
} else {
var limitY = container.scrollHeight - container.clientHeight;
if (scrollY > limitY) {
scrollY = limitY;
}
}
container.scrollTop = scrollY;
};
var removed = false;
container.addEventListener('mouseup', handleScrollReset, false);
container.addEventListener('mousedown', handleScrollReset, false);
container.addEventListener('mousewheel', handleMouseWheel, false);
return function() {
if (removed) {
return;
}
container.removeEventListener('mouseup', handleScrollReset, false);
container.removeEventListener('mousedown', handleScrollReset, false);
container.removeEventListener('mousewheel', handleMouseWheel, false);
removed = true;
};
}
implement it in the ngAfterViewInit function:
ngAfterViewInit(): void {
const el = document.querySelector<HTMLElement>('.cdk-virtual-scroll-viewport');
this.changeWheelSpeed(el, 0.99);
}

negative values missing in logarithmic mode

so after going all over other questions on SOF.
I'm using HighchartsReact wrapper for Highcharts.
Expected behaviour:
show negative values in stacked column chart even in logarithmic scale.
When toggling a series that has y values < 0, log scale hides them. When toggling back to linear scale the hidden points should be visible again.
Actual behaviour:
negative values disappear when going from linear to logarithmic. in addition when going back to linear the negative value that were seen in linear scale before - disappear and are not part of the chart.
It was working before several weeks and stopped working suddenly.
Live demo with steps to reproduce:
demo
official Custom Axis extension to allow emulation of
negative values on a logarithmic
Product version
9.3.2
How can I add this function with using HighchartsReact? I tried passing a callback and also inside React.useEffect to use the chart ref. but anything I do, still negative values are missing. and going back to linear just removes the original negative values from series.
(function (H) {
H.addEvent(H.Axis, 'afterInit', function () {
const logarithmic = this.logarithmic;
if (logarithmic && this.options.custom.allowNegativeLog) {
// Avoid errors on negative numbers on a log axis
this.positiveValuesOnly = false;
// Override the converter functions
logarithmic.log2lin = num => {
const isNegative = num < 0;
let adjustedNum = Math.abs(num);
if (adjustedNum < 10) {
adjustedNum += (10 - adjustedNum) / 10;
}
const result = Math.log(adjustedNum) / Math.LN10;
return isNegative ? -result : result;
};
logarithmic.lin2log = num => {
const isNegative = num < 0;
let result = Math.pow(10, Math.abs(num));
if (result < 10) {
result = (10 * (result - 1)) / (10 - 1);
}
return isNegative ? -result : result;
};
}
});
}(Highcharts));
You need to define the variable chart if you want to see how is changing.
const chart = Highcharts.chart('container', {
});
Live demo: https://jsfiddle.net/BlackLabel/x1zp347m/
Here is the official Highcharts React wrapper where you will find how to use Highcharts at the React.
https://github.com/highcharts/highcharts-react#basic-usage-example
EDIT --------------------------------------------------------------
To extending the chart custom code or edit the core you can fire function after imports.
How to extending Higcharts code:
https://www.highcharts.com/docs/extending-highcharts/extending-highcharts
import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
(function (H) {
H.addEvent(H.Chart, 'load', function (e) {
var chart = e.target;
H.addEvent(chart.container, 'click', function (e) {
e = chart.pointer.normalize(e);
console.log('Clicked chart at ' + e.chartX + ', ' + e.chartY);
});
H.addEvent(chart.xAxis[0], 'afterSetExtremes', function (e) {
console.log('Set extremes to ' + e.min + ', ' + e.max);
});
});
}(Highcharts));
const options = {
title: {
text: 'My chart'
},
plotOptions: {
series: {
enableMouseTracking: true
}
},
series: [{
data: [1, 2, 3]
}]
}
const App = () => <div>
<HighchartsReact
highcharts={Highcharts}
options={options}
/>
</div>
render(<App />, document.getElementById('root'))
https://stackblitz.com/edit/react-t6rh4c?file=components%2FChart.jsx

Reflections in Three Js

I have a bad problem to solve in an application react-based written with typescript that should manage 3D shapes.
The problem is that the reflections don't look good at all. I tried everything I can to better the code but nothing was successful.
The workflow is to create a material holder in a blender, export it and to apply to an empty shape imported from another gltf.
For all the materials I tried (paper, with normal map structure) everything works fine.
with simple paper material
In case the material is reflective (roughness 0.2 and metalness 0.8) this is the result:
with reflective material
As you can see the portion of the environment reflected is dramatically wrong if you think that the cube is a placeholder so done:
one of the six images of the cube map
The code is very simple, here I create the cube Map:
const loader = new THREE.CubeTextureLoader();
const path = `${this.props.baseUrl}backgrounds/${background.value}`;
const ext = background.value === "test" ? "jpg" : "png";
const bkcg = [
`${path}/py.${ext}`,
`${path}/nz.${ext}`,
`${path}/px.${ext}`,
`${path}/ny.${ext}`,
`${path}/pz.${ext}`,
`${path}/nx.${ext}`,
];
// const loader = new THREE.TextureLoader();
// const bkcg = `${this.props.baseUrl}backgrounds/test_texture.jpg`;
loader.load(bkcg, async (t) => {
t.minFilter = THREE.LinearFilter;
t.magFilter = THREE.LinearFilter;
t.encoding = THREE.sRGBEncoding;
t.format = THREE.RGBFormat;
this.setState({
background: t,
bckgLoaded: true,
});
Here I assign the material to the different meshes:
public editMeshes = (
item: THREE.Mesh,
isOrderPage: boolean,
design: IDesign,
materials: {[name: string]: THREE.MeshStandardMaterial | string},
textures: ITextures,
renderer: THREE.WebGLRenderer,
scene: THREE.Scene,
) => {
if (item.name === "Ground" || item.name === "X_Ground_Freigabe") {
const color = isOrderPage ? new THREE.Color("#ffffff") : new THREE.Color("#aaaaaa"); // #8f8f8f
const groundMaterial = new THREE.MeshBasicMaterial({ color });
item.material = groundMaterial;
} else {
item.scale.x = item.scale.x + 0;
item.scale.y = item.scale.y + 0;
item.scale.z = item.scale.z + 0;
if (Object.keys(design).indexOf(item.name) !== -1 || Object.keys(materials).indexOf(item.name) !== -1) {
if (Object.keys(design).indexOf(item.name) === -1 && Object.keys(materials).indexOf(item.name) !== -1) {
if (item.material instanceof THREE.MeshStandardMaterial) {
item.material.color = new THREE.Color(`${materials[item.name]}`);
}
} else {
if (typeof(materials[item.name]) !== "string") {
item.material = materials[item.name] as THREE.MeshStandardMaterial;
if (item.material instanceof THREE.MeshStandardMaterial) {
if (shinyMaterials.indexOf((item.material as THREE.MeshStandardMaterial).name) !== -1) {
this.createCubeCamera(item, textures, scene, renderer);
item.material.needsUpdate = true;
} else {
(item.material as THREE.MeshStandardMaterial).map = textures ? textures[item.name] :
(item.material as THREE.MeshStandardMaterial).map;
(item.material as THREE.MeshStandardMaterial).envMapIntensity = 4;
(item.material as THREE.MeshStandardMaterial).needsUpdate = true;
item.material.flatShading = false;
}
}
}
}
} else {
if (shinyMaterials.indexOf((item.material as THREE.MeshStandardMaterial).name) !== -1) {
this.createCubeCamera(item, textures, scene, renderer);
}
}
}
}
}
here I create the camera for the reflections:
public createCubeCamera = (
item: THREE.Mesh,
textures: ITextures,
scene: THREE.Scene,
renderer: THREE.WebGLRenderer) => {
const cubeCamera = new THREE.CubeCamera(0.001, 10000, 2048);
scene.add(cubeCamera);
cubeCamera.name = `cubeCamera_${item.name}`;
cubeCamera.position.set(item.position.x, item.position.y, item.position.z);
item.visible = false;
cubeCamera.update(renderer, scene);
item.visible = true;
const renderCamera = cubeCamera.renderTarget.texture as THREE.CubeTexture; // scene.background as THREE.CubeTexture
(item.material as THREE.MeshStandardMaterial).map =
textures ? textures[item.name] : (item.material as THREE.MeshStandardMaterial).map;
(item.material as THREE.MeshStandardMaterial).envMap = renderCamera;
(item.material as THREE.MeshStandardMaterial).envMapIntensity = 1;
(item.material as THREE.MeshStandardMaterial).flatShading = false;
(item.material as THREE.MeshStandardMaterial).needsUpdate = true;
}
and here I render the scene:
if (this.props.background) {
scene.background = this.props.background;
const camera = this.props.mainScene.cameras[0];
scene.children[0].children.map((item: THREE.Object3D) => {
if (item instanceof THREE.Light) {
this.props.mockUtils.editLights(
item as THREE.SpotLight | THREE.DirectionalLight,
this.props.scene.lights_intensity,
scene,
);
}
if (item instanceof THREE.Mesh) {
this.props.mockUtils.editMeshes(
item,
this.props.isOrderPage,
this.props.design,
this.props.materials,
this.props.textures,
// this.props.background,
renderer,
scene,
);
}
});
this.props.mockUtils.addAmbientLight(scene, this.props.scene.ambient_light);
scene.children.map((obj: THREE.Object3D) => {
if (obj instanceof THREE.CubeCamera) {
obj.update(renderer, scene);
}
});
renderer.render(scene, camera);
if (this.design.current) {
this.props.mockUtils.finish(
renderer,
FinalImage,
id,
`${this.props.baseUrl}products/${this.props.scene.product_name}.jpg`,
this.props.isOrderPage,
this.props.scene.zoomFactor,
this.design.current,
this.assetsLoaderCallback,
);
}
}
}
Can anyone help me to understand how to receive a normal reflection of the cube map that is applied to the scene background?
Thank you
Michael Moretti

Camera streaming service works only with localhost but not with IP address

I have implemented a service which streams camera output on html5. But it works only if I use localhost:8080 localhost if I use IP address or machine name then it does not even detect the camera.
/*global logger*/
/*
VisualInspection
========================
#file : VisualInspection.js
#version : 1.0.0
#author :
#date : 7/28/2019
#copyright :
#license : Apache 2
Documentation
========================
Describe your widget here.
*/
// Required module list. Remove unnecessary modules, you can always get them back from the boilerplate.
define([
"dojo/_base/declare",
"mxui/widget/_WidgetBase",
"dijit/_TemplatedMixin",
"mxui/dom",
"dojo/dom",
"dojo/dom-prop",
"dojo/dom-geometry",
"dojo/dom-class",
"dojo/dom-style",
"dojo/dom-construct",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/text",
"dojo/html",
"dojo/_base/event",
"VisualInspection/lib/jquery-1.11.2",
"dojo/text!VisualInspection/widget/template/VisualInspection.html",
"VisualInspection/widget/template/tf.min",
// "dojo/text!VisualInspection/widget/template/labels.json",
// "dojo/text!VisualInspection/widget/template/model.json"
], function (declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, dojoProp, dojoGeometry, dojoClass, dojoStyle, dojoConstruct, dojoArray, lang, dojoText, dojoHtml, dojoEvent, _jQuery, widgetTemplate, tf) {
"use strict";
var $ = _jQuery.noConflict(true);
var LABELS_URL = "http://pni6w2465:7777/EasyPlan/model_web/labels.json"
var MODEL_JSON = "http://pni6w2465:7777/EasyPlan/model_web/model.json"
// var tf = require(['../../VisualInspection/node_modules/#tensorflow/tfjs']);
//////////////
const TFWrapper = model => {
const calculateMaxScores = (scores, numBoxes, numClasses) => {
const maxes = []
const classes = []
for (let i = 0; i < numBoxes; i++) {
let max = Number.MIN_VALUE
let index = -1
for (let j = 0; j < numClasses; j++) {
if (scores[i * numClasses + j] > max) {
max = scores[i * numClasses + j]
index = j
}
}
maxes[i] = max
classes[i] = index
}
return [maxes, classes]
}
const buildDetectedObjects = (
width,
height,
boxes,
scores,
indexes,
classes
) => {
const count = indexes.length
const objects = []
for (let i = 0; i < count; i++) {
const bbox = []
for (let j = 0; j < 4; j++) {
bbox[j] = boxes[indexes[i] * 4 + j]
}
const minY = bbox[0] * height
const minX = bbox[1] * width
const maxY = bbox[2] * height
const maxX = bbox[3] * width
bbox[0] = minX
bbox[1] = minY
bbox[2] = maxX - minX
bbox[3] = maxY - minY
objects.push({
bbox: bbox,
class: classes[indexes[i]],
score: scores[indexes[i]]
})
}
return objects
}
var img = null;
const detect = input => {
const batched = tf.tidy(() => {
const img = tf.browser.fromPixels(input)
// Reshape to a single-element batch so we can pass it to executeAsync.
// var img = null;
// //sid
// var canvas = document.querySelector("#canvasElement");
// if (canvas.getContext) {
// var ctx = canvas.getContext("2d");
// img = canvas.toDataURL("image/png");
// }
return img.expandDims(0)
})
const height = batched.shape[1]
const width = batched.shape[2]
// const height = img.height
// const width = img.width
return model.executeAsync(batched).then(result => {
const scores = result[0].dataSync()
const boxes = result[1].dataSync()
// clean the webgl tensors
batched.dispose()
tf.dispose(result)
const [maxScores, classes] = calculateMaxScores(
scores,
result[0].shape[1],
result[0].shape[2]
)
const prevBackend = tf.getBackend()
// run post process in cpu
tf.setBackend('cpu')
const indexTensor = tf.tidy(() => {
const boxes2 = tf.tensor2d(boxes, [
result[1].shape[1],
result[1].shape[3]
])
return tf.image.nonMaxSuppression(
boxes2,
maxScores,
20, // maxNumBoxes
0.5, // iou_threshold
0.5 // score_threshold
)
})
const indexes = indexTensor.dataSync()
indexTensor.dispose()
// restore previous backend
tf.setBackend(prevBackend)
return buildDetectedObjects(
width,
height,
boxes,
maxScores,
indexes,
classes
)
})
}
return {
detect: detect
}
}
//////////////////////
// Declare widget's prototype.
return declare("VisualInspection.widget.VisualInspection", [_WidgetBase, _TemplatedMixin], {
// _TemplatedMixin will create our dom node using this HTML template.
templateString: widgetTemplate,
// DOM elements
inputNodes: null,
colorSelectNode: null,
colorInputNode: null,
infoTextNode: null,
// Parameters configured in the Modeler.
mfToExecute: "",
messageString: "",
backgroundColor: "",
// Internal variables. Non-primitives created in the prototype are shared between all widget instances.
_handles: null,
_contextObj: null,
_alertDiv: null,
_readOnly: false,
// dojo.declare.constructor is called to construct the widget instance. Implement to initialize non-primitive properties.
constructor: function () {
logger.debug(this.id + ".constructor");
this._handles = [];
},
// dijit._WidgetBase.postCreate is called after constructing the widget. Implement to do extra setup work.
postCreate: function () {
logger.debug(this.id + ".postCreate");
if (this.readOnly || this.get("disabled") || this.readonly) {
this._readOnly = true;
}
this._updateRendering();
this._setupEvents();
var video = document.querySelector("#videoElement");
var canvas = document.querySelector("#canvasElement");
// if (navigator.mediaDevices.getUserMedia) {
// navigator.mediaDevices.getUserMedia({ video: true })
// .then(function (stream) {
// video.srcObject = stream;
// })
// .catch(function (err0r) {
// console.log("Something went wrong!");
// });
// }
this.componentDidMount();
},
////////////////////////////////////////////////////////
componentDidMount: function () {
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
const webCamPromise = navigator.mediaDevices
.getUserMedia({
audio: false,
video: {
facingMode: 'user'
}
})
.then(stream => {
window.stream = stream
video.srcObject = stream
return new Promise((resolve, _) => {
video.onloadedmetadata = () => {
resolve()
}
})
})
const modelPromise = tf.loadGraphModel(MODEL_JSON)
const labelsPromise = fetch(LABELS_URL).then(data => data.json())
Promise.all([modelPromise, labelsPromise, webCamPromise])
.then(values => {
const [model, labels] = values
this.detectFrame(video, model, labels)
})
.catch(error => {
console.error(error)
})
}
},
detectFrame: function (video, model, labels) {
TFWrapper(model)
.detect(video)
.then(predictions => {
this.renderPredictions(predictions, labels)
requestAnimationFrame(() => {
this.detectFrame(video, model, labels)
})
})
},
renderPredictions: function (predictions, labels) {
var canvas = document.querySelector("#canvasElement");
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
// Font options.
const font = '16px sans-serif'
ctx.font = font
ctx.textBaseline = 'top'
predictions.forEach(prediction => {
const x = prediction.bbox[0]
const y = prediction.bbox[1]
const width = prediction.bbox[2]
const height = prediction.bbox[3]
const label = labels[parseInt(prediction.class)]
// Draw the bounding box.
ctx.strokeStyle = '#00FFFF'
ctx.lineWidth = 4
ctx.strokeRect(x, y, width, height)
// Draw the label background.
ctx.fillStyle = '#00FFFF'
const textWidth = ctx.measureText(label).width
const textHeight = parseInt(font, 10) // base 10
ctx.fillRect(x, y, textWidth + 4, textHeight + 4)
})
predictions.forEach(prediction => {
const x = prediction.bbox[0]
const y = prediction.bbox[1]
const label = labels[parseInt(prediction.class)]
// Draw the text last to ensure it's on top.
ctx.fillStyle = '#000000'
ctx.fillText(label, x, y)
})
},
///////////////////////////////////////////////////////////
// mxui.widget._WidgetBase.update is called when context is changed or initialized. Implement to re-render and / or fetch data.
update: function (obj, callback) {
logger.debug(this.id + ".update");
this._contextObj = obj;
this._resetSubscriptions();
this._updateRendering(callback); // We're passing the callback to updateRendering to be called after DOM-manipulation
},
// mxui.widget._WidgetBase.enable is called when the widget should enable editing. Implement to enable editing if widget is input widget.
enable: function () {
logger.debug(this.id + ".enable");
},
// mxui.widget._WidgetBase.enable is called when the widget should disable editing. Implement to disable editing if widget is input widget.
disable: function () {
logger.debug(this.id + ".disable");
},
// mxui.widget._WidgetBase.resize is called when the page's layout is recalculated. Implement to do sizing calculations. Prefer using CSS instead.
resize: function (box) {
logger.debug(this.id + ".resize");
},
// mxui.widget._WidgetBase.uninitialize is called when the widget is destroyed. Implement to do special tear-down work.
uninitialize: function () {
logger.debug(this.id + ".uninitialize");
// Clean up listeners, helper objects, etc. There is no need to remove listeners added with this.connect / this.subscribe / this.own.
},
// We want to stop events on a mobile device
_stopBubblingEventOnMobile: function (e) {
logger.debug(this.id + "._stopBubblingEventOnMobile");
if (typeof document.ontouchstart !== "undefined") {
dojoEvent.stop(e);
}
},
// Attach events to HTML dom elements
_setupEvents: function () {
logger.debug(this.id + "._setupEvents");
this.connect(this.colorSelectNode, "change", function (e) {
// Function from mendix object to set an attribute.
this._contextObj.set(this.backgroundColor, this.colorSelectNode.value);
});
this.connect(this.infoTextNode, "click", function (e) {
// Only on mobile stop event bubbling!
this._stopBubblingEventOnMobile(e);
// If a microflow has been set execute the microflow on a click.
if (this.mfToExecute !== "") {
this._execMf(this.mfToExecute, this._contextObj.getGuid());
}
});
},
_execMf: function (mf, guid, cb) {
logger.debug(this.id + "._execMf");
if (mf && guid) {
mx.ui.action(mf, {
params: {
applyto: "selection",
guids: [guid]
},
callback: lang.hitch(this, function (objs) {
if (cb && typeof cb === "function") {
cb(objs);
}
}),
error: function (error) {
console.debug(error.description);
}
}, this);
}
},
// Rerender the interface.
_updateRendering: function (callback) {
logger.debug(this.id + "._updateRendering");
// Important to clear all validations!
this._clearValidations();
// The callback, coming from update, needs to be executed, to let the page know it finished rendering
this._executeCallback(callback, "_updateRendering");
},
// Handle validations.
_handleValidation: function (validations) {
logger.debug(this.id + "._handleValidation");
this._clearValidations();
var validation = validations[0],
message = validation.getReasonByAttribute(this.backgroundColor);
if (this._readOnly) {
validation.removeAttribute(this.backgroundColor);
} else if (message) {
this._addValidation(message);
validation.removeAttribute(this.backgroundColor);
}
},
// Clear validations.
_clearValidations: function () {
logger.debug(this.id + "._clearValidations");
dojoConstruct.destroy(this._alertDiv);
this._alertDiv = null;
},
// Show an error message.
_showError: function (message) {
logger.debug(this.id + "._showError");
if (this._alertDiv !== null) {
dojoHtml.set(this._alertDiv, message);
return true;
}
this._alertDiv = dojoConstruct.create("div", {
"class": "alert alert-danger",
"innerHTML": message
});
dojoConstruct.place(this._alertDiv, this.domNode);
},
// Add a validation.
_addValidation: function (message) {
logger.debug(this.id + "._addValidation");
this._showError(message);
},
// Reset subscriptions.
_resetSubscriptions: function () {
logger.debug(this.id + "._resetSubscriptions");
// Release handles on previous object, if any.
this.unsubscribeAll();
// When a mendix object exists create subscribtions.
if (this._contextObj) {
this.subscribe({
guid: this._contextObj.getGuid(),
callback: lang.hitch(this, function (guid) {
this._updateRendering();
})
});
this.subscribe({
guid: this._contextObj.getGuid(),
attr: this.backgroundColor,
callback: lang.hitch(this, function (guid, attr, attrValue) {
this._updateRendering();
})
});
this.subscribe({
guid: this._contextObj.getGuid(),
val: true,
callback: lang.hitch(this, this._handleValidation)
});
}
},
_executeCallback: function (cb, from) {
logger.debug(this.id + "._executeCallback" + (from ? " from " + from : ""));
if (cb && typeof cb === "function") {
cb();
}
}
});
});
require(["VisualInspection/widget/VisualInspection"]);
<div id="container">
<video autoplay="true" playsInline="true" width="600" height="500" id="videoElement" style="position: fixed;" >
</video>
<canvas id= "canvasElement" width="600" height="500" style="position: absolute;">
</canvas>
</div>
From Above code, When I run using localhost this code will execute :
<!-- begin snippet: js hide: false console: true babel: false -->
When I run using machine name or IP name :
This code is not considered in developer tool of chrome due to security or some reason

How to use Babylonjs in Reactjs Application?

I have tried import babylonjs in react but its is not working. Does any body know how to import and use the babylonjs in reactjs application.
Thanks.
Not sure if you have found the answer on your own, however there are several ways now as babylon has matured. There is actually a Node package for using babylon.js with react here: https://www.npmjs.com/package/react-babylonjs
Also there is an install guide for React in Babylon.js in the docs:
https://doc.babylonjs.com/resources/babylonjs_and_reactjs
Hope that helps!
Babylon JS is available as npm package. You can easily build a simple React Component around a canvas and Babylon JS
I have created a minimal example with React+ Babylon:
/* Babylon JS is available as **npm** package.
You can easily build a simple `React` Component around a `canvas` and Babylon JS
I have created a minimal example with React+ Babylon:
*/
import React, { Component } from "react";
import * as BABYLON from "babylonjs";
var scene;
var boxMesh;
/**
* Example temnplate of using Babylon JS with React
*/
class BabylonScene extends Component {
constructor(props) {
super(props);
this.state = { useWireFrame: false, shouldAnimate: false };
}
componentDidMount = () => {
// start ENGINE
this.engine = new BABYLON.Engine(this.canvas, true);
//Create Scene
scene = new BABYLON.Scene(this.engine);
//--Light---
this.addLight();
//--Camera---
this.addCamera();
//--Meshes---
this.addModels();
//--Ground---
this.addGround();
// Add Events
window.addEventListener("resize", this.onWindowResize, false);
// Render Loop
this.engine.runRenderLoop(() => {
scene.render();
});
//Animation
scene.registerBeforeRender(() => {
boxMesh.rotation.y += 0.01;
boxMesh.rotation.x += 0.01;
});
};
componentWillUnmount() {
window.removeEventListener("resize", this.onWindowResize, false);
}
onWindowResize = event => {
this.engine.resize();
};
/**
* Add Lights
*/
addLight = () => {
//---------- LIGHT---------------------
// Create a basic light, aiming 0,1,0 - meaning, to the sky.
var light = new BABYLON.HemisphericLight(
"light1",
new BABYLON.Vector3(0, 10, 0),
scene
);
};
/**
* Add Camera
*/
addCamera = () => {
// ---------------ArcRotateCamera or Orbit Control----------
var camera = new BABYLON.ArcRotateCamera(
"Camera",
Math.PI / 2,
Math.PI / 4,
4,
BABYLON.Vector3.Zero(),
scene
);
camera.inertia = 0;
camera.angularSensibilityX = 250;
camera.angularSensibilityY = 250;
// This attaches the camera to the canvas
camera.attachControl(this.canvas, true);
camera.setPosition(new BABYLON.Vector3(5, 5, 5));
};
/**
* Create Stage and Skybox
*/
addGround = () => {
// Create a built-in "ground" shape.
var ground = BABYLON.MeshBuilder.CreateGround(
"ground1",
{ height: 6, width: 6, subdivisions: 2 },
scene
);
var groundMaterial = new BABYLON.StandardMaterial("grass0", scene);
groundMaterial.diffuseTexture = new BABYLON.Texture(
"./assets/ground.jpeg",
scene
);
ground.material = groundMaterial;
//Add SkyBox
var photoSphere = BABYLON.Mesh.CreateSphere("skyBox", 16.0, 50.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("smat", scene);
skyboxMaterial.emissiveTexture = new BABYLON.Texture(
"assets/skybox.jpeg",
scene,
1,
0
);
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.emissiveTexture.uOffset = -Math.PI / 2; // left-right
skyboxMaterial.emissiveTexture.uOffset = 0.1; // up-down
skyboxMaterial.backFaceCulling = false;
photoSphere.material = skyboxMaterial;
};
/**
* Add Models
*/
addModels = () => {
// Add BOX
boxMesh = BABYLON.MeshBuilder.CreateBox(
"box",
{ height: 1, width: 1, depth: 1 },
scene
);
boxMesh.position.y = 1;
var woodMaterial = new BABYLON.StandardMaterial("wood", scene);
woodMaterial.diffuseTexture = new BABYLON.Texture(
"./assets/portal_cube.png",
scene
);
boxMesh.material = woodMaterial;
};
render() {
return (
<canvas
style={{ width: window.innerWidth, height: window.innerHeight }}
ref={canvas => {
this.canvas = canvas;
}}
/>
);
}
}
export default BabylonScene;
Live Demo:
https://codesandbox.io/s/babylonjs-react-template-w2i1k

Resources