SciChart: Working with Zooming module is not working - scichart

I am using SciChart Library for showing Graphs.
I want to know, how can I use MouseWheelZoomModifier module of SciChart library in my pure HTML & CSS based website.
I know there is a documentation available related to React but I am not using it in my Website.
I have written the following Code:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Include SciChart.js -->
<script
src="https://cdn.jsdelivr.net/npm/scichart#2.1.2290/_wasm/scichart.browser.js"
crossorigin="anonymous"
></script>
<title>Hello, SciChart.js world!</title>
</head>
<body>
<h1>Hello, SciChart.js world!</h1>
<!-- Create the Div to host the SciChartSurface -->
<div id="scichart-root" style="width: 800px; height: 600px;"></div>
<!-- The JavaScript to create a SciChartSurface -->
<script>
async function initSciChart() {
// In order to load data file from the CDN we need to set dataUrl
SciChart.SciChartSurface.configure({
dataUrl: `https://cdn.jsdelivr.net/npm/scichart#${SciChart.libraryVersion}/_wasm/scichart2d.data`,
wasmUrl: `https://cdn.jsdelivr.net/npm/scichart#${SciChart.libraryVersion}/_wasm/scichart2d.wasm`
});
// Create a SciChartSurface inside the div with id 'scichart-root'
const {
sciChartSurface,
wasmContext
} = await SciChart.SciChartSurface.create("scichart-root");
// Add an X and a Y Axis
const xAxis = new SciChart.NumericAxis(wasmContext);
sciChartSurface.xAxes.add(xAxis);
const yAxis = new SciChart.NumericAxis(wasmContext);
sciChartSurface.yAxes.add(yAxis);
// Create 100 dataseries, each with 10k points
for (let seriesCount = 0; seriesCount < 100; seriesCount++) {
const xyDataSeries = new SciChart.XyDataSeries(wasmContext);
const opacity = (1 - ((seriesCount / 120))).toFixed(2);
// Populate with some data
for(let i = 0; i < 10000; i++) {
xyDataSeries.append(i, Math.sin(i* 0.01) * Math.exp(i*(0.00001*(seriesCount+1))));
}
// Add and create a line series with this data to the chart
// Create a line series
const lineSeries = new SciChart.FastLineRenderableSeries(wasmContext, {
dataSeries: xyDataSeries,
stroke: `rgba(176,196,222,${opacity})`,
strokeThickness:2
});
sciChartSurface.renderableSeries.add(lineSeries);
}
// BELOW ONE NOT WORKING
// Add zoom, pan behaviours to the chart. Mousewheel zoom, panning and double-click to
// zoom to fit
const mouseWheelZoomModifier = new MouseWheelZoomModifier();
const zoomPanModifier = new ZoomPanModifier();
const rubberBandZoomModifier = new RubberBandXyZoomModifier();
const zoomExtentsModifier = new ZoomExtentsModifier();
sciChartSurface.chartModifiers.add(zoomExtentsModifier);
sciChartSurface.chartModifiers.add(zoomPanModifier);
sciChartSurface.chartModifiers.add(rubberBandZoomModifier);
sciChartSurface.chartModifiers.add(mouseWheelZoomModifier);
const inputEnablePan = document.getElementById("enable-pan");
const inputEnableZoom = document.getElementById("enable-zoom");
const inputEnableZoomToFit = document.getElementById("enable-zoom-to-fit");
const inputEnableMouseWheel = document.getElementById("enable-mouse-wheel-zoom");
inputEnablePan.addEventListener("input", (event) => {
zoomPanModifier.isEnabled = inputEnablePan.checked;
rubberBandZoomModifier.isEnabled = !inputEnablePan.checked;
inputEnableZoom.checked = !inputEnablePan.checked;
console.log(`Enabling Drag to Pan. Status: rubberBand checkbox ${inputEnableZoom.checked}, rubberBand ${rubberBandZoomModifier.isEnabled}, zoomPan checkbox ${inputEnablePan.isEnabled}, zoomPan ${zoomPanModifier.isEnabled} `);
});
inputEnableZoom.addEventListener("input", (event) => {
rubberBandZoomModifier.isEnabled = inputEnableZoom.checked;
zoomPanModifier.isEnabled = !inputEnableZoom.checked;
inputEnablePan.checked = !inputEnableZoom.checked;
console.log(`Enabling Drag to Zoom. Status: rubberBand checkbox ${inputEnableZoom.checked}, rubberBand ${rubberBandZoomModifier.isEnabled}, zoomPan checkbox ${inputEnablePan.isEnabled}, zoomPan ${zoomPanModifier.isEnabled} `);
});
inputEnableZoomToFit.addEventListener("input", (event) => {
zoomExtentsModifier.isEnabled = inputEnableZoomToFit.checked;
console.log("Enabling zoom extents");
});
inputEnableMouseWheel.addEventListener("input", (event) => {
mouseWheelZoomModifier.isEnabled = inputEnableMouseWheel.checked;
console.log("Enabling Mousewheel zoom");
});
}
initSciChart();
</script>
</body>
</html>
Output:
The MouseWheelZoomModifier is actually the module that is import using import keyword in React tutorial but how can I use it in HTML & CSS based Web Page.
Kindly Help.

Because you are using SciChart's Browser module (where the code is served from CDN and JS rather than npm/webpack) you need to use a slightly different way to declare objects in code.
Note the Tutorial for setting up SciChart.js with browser module says
Notice every API call is prefixed by SciChart. when using the browser bundle. This is the global namespace for all SciChart apis, functions and types.
Once you have added the script to include scichart.js (and version)
<script src="https://cdn.jsdelivr.net/npm/scichart#2.1.2290/_wasm/scichart.browser.js" crossorigin="anonymous"></script>
You must now tell SciChart where to load the wasm files from. The easiest way to do this is to call SciChartSurface.useWasmFromCDN();
SciChart.SciChartSurface.useWasmFromCDN();
Next, when not using npm/webpack every type in the SciChart library is now prepended with the global variable SciChart.
For example in our npm/webpack docs this code:
const mouseWheelZoomModifier = new MouseWheelZoomModifier();
sciChartSurface.chartModifiers.add(mouseWheelZoomModifier);
must become this
const mouseWheelZoomModifier = new SciChart.MouseWheelZoomModifier();
sciChartSurface.chartModifiers.add(mouseWheelZoomModifier);
Alternatively you can pre-declare these types as follows:
// When using SciChart from CDN / browser bundle, there are no imports
// so either prepend every variable by global namespace SciChart.
// or use code like this to get the types out
const {
MouseWheelZoomModifier,
SciChartSurface,
NumericAxis
} = SciChart;
// static func. Call once. load wasm from CDN
SciChartSurface.useWasmFromCDN();
// Create a SciChartSurface in <div id="div-id"/>
const { sciChartSurface, wasmContext } = SciChartSurface.create("div-id");
// Add x,y axis
sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext));
// Add modifiers for zooming, panning
const mouseWheelZoomModifier = new MouseWheelZoomModifier();
sciChartSurface.chartModifiers.add(mouseWheelZoomModifier);
Try that and see if it works

Related

Clear canvas drawpad jquery

I'm using the drawing pad (pen tool) plugin of Jquery to draw with different colors and having an image in the canvas as background. My purpose is to have a button to clear the drawing over the canvas. The way I try to do it remove the background image along with the drawing. How can I keep the background and remove the drawing on clicking the clear button ?
My fiddle : https://jsfiddle.net/ub3s9go7/
<script>
$(document).ready(function() {
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var contextCanvas = $("#target canvas").get(0).getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
}
// Need to clear only the drawing not the background image
$("#clearDrawing").click(function() {
contextCanvas.clearRect(0, 0, 750, 423);
});
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<style>
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="clearDrawing">Clear Drawing</button>
<div id="target" class="drawpad-dashed"></div>
</body>
</html>
This answer is an improvisation on my previous answer at https://stackoverflow.com/a/67155647/3706717
So we have new requirement: delete/clear previous drawings
There are some possible approach here:
#sinisake in comment suggested to reload the background so that we have fresh canvas with only the background intact (but for some reason, white doodle make the background gone)
the library must have "delete" or "erase" doodle feature (which it didn't have)
save each changes of the drawing when user click "save", so that user can "undo" to previous version of the drawing (like git's git commit and git reset command), I'll be using this approach in my answer
Ideally, you should use server-side language and persistent storage (e.g.: database) to store user's doodling history. But in this case, to simulate such thing I'll be using javascript's localStorage API https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
So every time I'm calling localStorage API, just assume that I'm calling some ajax to some endpoint.
Fiddle: https://jsfiddle.net/0da572jy/3/
Here is stack fiddle (modified because browser didn't allow stack fiddle to use localStorage)
// polyfill for localStorage API
var localStorage1 = {
items: {},
removeItem: function(key) {
window.localStorage1.items[key] = null;
},
getItem: function(key) {
return window.localStorage1.items[key];
},
setItem: function(key, val) {
return window.localStorage1.items[key] = val;
},
}
//window.localStorage = localStorage1;
window.localStorage1 = localStorage1;
$(document).ready(function() {
$("#save").click(function() {
// I already explained the #save logic in https://stackoverflow.com/a/67155647/3706717
//console.log("save");
var base64Image = $("#target canvas").get(0).toDataURL();
//console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
// load/read saved states/histories
var savedImageJson = window.localStorage1.getItem("savedImage");
//console.log(savedImageJson);
// if the history is undefined, create empty array
if(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
// parse the history
var savedImageArr = JSON.parse(savedImageJson);
// add current state as a new item to history
savedImageArr.push(base64Image);
// save the modified (added history)
window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
$("#numOfSavedHistory").html( savedImageArr.length );
});
// clear button just clears the localStorage (or any kind of API you use for persistent storage
$("#clear").click(function() {
//console.log("save");
window.localStorage1.removeItem("savedImage");
$("#numOfSavedHistory").html( 0 );
});
// undo last change (rollback to last state when you clicked save)
$("#undo").click(function() {
// clear canvas (to prevent white ink bug that also clears the background)
canvas.width = canvas.width;
//console.log("undo");
// load/read saved states/histories
var savedImageJson = window.localStorage1.getItem("savedImage");
//console.log(savedImageJson);
// if the history is undefined, create empty array
if(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
// parse the history
var savedImageArr = JSON.parse(savedImageJson);
// delete last item in history
savedImageArr.pop();
// save the modified (pop'ed history)
window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
// draw old picture on canvas
var imageOld = new Image();
imageOld.src = savedImageArr[savedImageArr.length-1];
imageOld.onload = function() {
contextCanvas.drawImage(imageOld, 0, 0);
};
$("#numOfSavedHistory").html( savedImageArr.length );
});
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
//imageBackground.crossorigin = "anonymous";
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var canvas = $("#target canvas").get(0);
var contextCanvas = canvas.getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
$("#clear").trigger("click"); // clear previous drawings when page refreshed
$("#save").trigger("click"); // save the first image (background only)
}
});
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="undo">Undo</button>
<button id="save">Save</button>
<button id="clear">Clear Saved Picture</button>
<span id="numOfSavedHistory">0</span>
<div id="target" class="drawpad-dashed"></div>
<div id="outputBase64"></div>
</body>
</html>

Here maps not draggable in ms access webbrowser

I have created a simple html using the draggable marker example from here maps. I have adapted it to support IE 11 by adding reference to legacy js, meta tag and using P2D engine in map options. Also added two url parameters for coordinates. It works perfectly in IE11 and it loads and shows pan and zoom buttons in ms-access webbrowser but it keeps static, it's not draggable, but pan and zoom works.
The curious thing is that if I navigate to wego.here.com in the same webbrowser control then the map is draggable. So they're doing something else in the here maps main page that I'm not doing in my script.
I have also tried using Microsoft Web Browser from the activex controls list in access.
I need it to be draggable so I can pick the coordinates after the user changes the marker position.
This is my script:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Draggable Marker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<style>
html, body { margin:0px; padding:0px; width: 100%; height: 100%; }
.main { height: 100%; }
</style>
</head>
<body id="markers-on-the-map">
<div class="main" style="width:100%" id="map"></div>
<input type="hidden" id="long" name="long">
<input type="hidden" id="lat" name="lat">
<script>
function addDraggableMarker(map, behavior){
var marker = new H.map.Marker({lat:latitud, lng:longitud}, {volatility: true});
// Ensure that the marker can receive drag events
marker.draggable = true;
map.addObject(marker);
// disable the default draggability of the underlying map
// and calculate the offset between mouse and target's position
// when starting to drag a marker object:
map.addEventListener('dragstart', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
var targetPosition = map.geoToScreen(target.getGeometry());
target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
behavior.disable();
}
}, false);
// re-enable the default draggability of the underlying map
// when dragging has completed
map.addEventListener('dragend', function(ev) {
var target = ev.target;
if (target instanceof H.map.Marker) {
$('#long').val(ev.target.b.lng);
$('#lat').val(ev.target.b.lat);
behavior.enable();
}
}, false);
// Listen to the drag event and move the position of the marker
// as necessary
map.addEventListener('drag', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
target.setGeometry(map.screenToGeo(pointer.viewportX - target['offset'].x, pointer.viewportY - target['offset'].y));
}
}, false);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: '?????????????????????????????????'
});
var defaultLayers = platform.createDefaultLayers();
//url parameters
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
var latitud=query_string.lat;
var longitud=query_string.long;
//Step 2: initialize a map - this map is centered over Boston
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.normal.map, {
center: {lat:latitud, lng:longitud},
engineType: H.map.render.RenderEngine.EngineType.P2D,
zoom: 12,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
//window.addEventListener('resize', () => map.getViewPort().resize());
window.addEventListener('resize', function () {map.getViewPort().resize(); });
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
//var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Add the click event listener.
addDraggableMarker(map, behavior);
</script>
</body>
</html>```
Check please on this static page
: your code works for my IE11

Injecting a custom element in HTML5 then retrieving its value using XPath comes back blank

I'm injecting an XML string generated from a web service, then trying to use XPath to query the attribute values using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>tox-js</title>
</head>
<body>
<script>
//
// -----------------------------------------------
// tox element
class Tox extends HTMLElement
{
constructor(url)
{
super();
fetch(url)
.then((response)=>
{
console.log("status: "+response.status);
return response.text();
})
.then((text)=>
{
console.log("text: "+text);
try
{
var dp = new DOMParser();
var xmlDOM = dp.parseFromString(text, "text/xml");
this.appendChild(xmlDOM.documentElement);
return true;
}
catch(err)
{
console.log("err: "+err.message);
return false;
}
})
.then((ok)=>
{
if (ok)
{
try
{
var xpe = new XPathEvaluator();
var txt = xpe.evaluate("//tox-js/example/#timestamp",document,null,XPathResult.STRING_TYPE,null);
console.log("//tox-js/example/#timestamp: "+txt.stringValue);
txt = xpe.evaluate("//tox-js/example/#feedback",document,null,XPathResult.STRING_TYPE,null);
console.log("//tox-js/example/#feedback: "+txt.stringValue);
}
catch(err)
{
console.log("err: "+err.message);
}
}
else
console.log("not ok");
}
);
}
}
//
// -----------------------------------------------
// register our element with the DOM
customElements.define('tox-js',Tox);
//
// -----------------------------------------------
// create an instance and add it to the body
document.body.appendChild(new Tox('http://localhost:8080/tox/example.test.formatted?in_mask=YYYYMMDD'));
// -----------------------------------------------
//
</script>
</body>
</html>
The result has the custom element injected.
<html lang="en">
<head>...</head>
<body>
<script>...</script>
<tox-js>
<example timestamp="20180103142036" feedback="ok">20190103</example>
</tox-js>
</body>
<html>
The console log confirms the return status and XML, but the result of the XPath is blank.
[Log] status: 200 (toxElement3.html, line 20)
[Log] text: <example timestamp="20190103142036" feedback="ok">20190103</example> (toxElement3.html, line 25)
[Log] //tox-js/example/#timestamp: (toxElement3.html, line 47)
[Log] //tox-js/example/#feedback: (toxElement3.html, line 49)
Where have I gone wrong? This should not be a timing issue since I'm using .then to wait for the previous step.
Seems it is related to the namespaces.
The following XPath works for me:
//tox-js/*[local-name()='example']/#timestamp
Check this answer:
XPath Doesn't Work in Dynamic HTML-Document
Also you can use document.createElement() or insertAdjacentHTML() to create element from text as described here: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
In this case your XPath will work as expected.
<html lang="en">
<head></head>
<body>
<script>
window.addEventListener('load', () => {
var text = `<example timestamp="20180103142036" feedback="ok">20190103</example>`;
var el = document.getElementsByTagName('tox-js')[0];
el.insertAdjacentHTML('afterbegin', text);
var xpe = new XPathEvaluator();
var txt = xpe.evaluate("//tox-js/example/#timestamp",document,null,XPathResult.STRING_TYPE,null);
console.log(`//tox-js/example/#timestamp: ${txt.stringValue}`);
});
</script>
<tox-js>
</tox-js>
</body>
<html>
P.S. I can't explain why the problem happens when using DOMParser. Maybe there are different namespaces for document and DOMParser. So if somebody has more details, feel free to extend the answer.
From the provided example...
var dp = new DOMParser();
var xmlDOM = dp.parseFromString(text, "text/xml");
this.appendChild(xmlDOM.documentElement);
...becomes...
this.insertAdjacentHTML('afterbegin', text);

WebVR Extension with Basic Application Example

I am trying to use the WebVR extension with a basic application. Instead of a 3D model in VR, the below html renders a 2D model. The code is mostly boilerplate except for where I call the WebVR extension. Thanks in advance!
<!DOCTYPE html>
<!-- vr.html -->
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<!-- The Viewer CSS -->
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.min.css" type="text/css">
<!-- Developer CSS -->
<style>
body {
margin: 0;
}
#MyViewerDiv {
width: 100%;
height: 100%;
margin: 0;
background-color: #F0F8FF;
}
</style>
</head>
<body>
<!-- The Viewer will be instantiated here -->
<div id="MyViewerDiv"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/three.min.js"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js"></script>
<!-- Developer JS -->
<script>
var viewerApp;
var options = {
env: 'AutodeskProduction',
// Here is the WebVR extension
extensions: ['Autodesk.Viewing.WebVR'],
getAccessToken: function(onGetAccessToken) {
//
// TODO: Replace static access token string below with call to fetch new token from your backend
// Both values are provided by Forge's Authentication (OAuth) API.
//
// Example Forge's Authentication (OAuth) API return value:
// {
// "access_token": "<YOUR_APPLICATION_TOKEN>",
// "token_type": "Bearer",
// "expires_in": 86400
// }
//
var accessToken = {{ accessToken }};
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
}
};
var documentId = {{ documentID }};
// var config = {
// extensions: ['Autodesk.Viewing.WebVR'],
// experimental: ['webVR_orbitModel']
// };
Autodesk.Viewing.Initializer(options, function(){
viewerApp = new Autodesk.Viewing.ViewingApplication('MyViewerDiv');
viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
viewerApp.loadDocument(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
});
function onDocumentLoadSuccess(doc) {
// We could still make use of Document.getSubItemsWithProperties()
// However, when using a ViewingApplication, we have access to the **bubble** attribute,
// which references the root node of a graph that wraps each object from the Manifest JSON.
var viewables = viewerApp.bubble.search({'type':'geometry'});
if (viewables.length === 0) {
console.error('Document contains no viewables.');
return;
}
// Choose any of the avialble viewables
viewerApp.selectItem(viewables[0].data, onItemLoadSuccess, onItemLoadFail);
}
function onDocumentLoadFailure(viewerErrorCode) {
console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode);
}
function onItemLoadSuccess(viewer, item) {
console.log('onItemLoadSuccess()!');
console.log(viewer);
console.log(item);
// Congratulations! The viewer is now ready to be used.
console.log('Viewers are equal: ' + (viewer === viewerApp.getCurrentViewer()));
}
function onItemLoadFail(errorCode) {
console.error('onItemLoadFail() - errorCode:' + errorCode);
}
</script>
</body>
</html>
Where {{ documentID }} is my urn and {{ accessToken }} is my token.
First of all, I don't think the WebVR extension works for 2D model, I just tried with a f2d file, and it's not working, what do you expect for 2D in VR?
I also suggest you to use the Viewer version at least 2.13, if you do not specify any version of viewer, it will use 2.12 by default as I tried. And if you check the viewer 2.12 code of WebVR extension at https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.js?v=2.12, you will see it does not use webvr-polyfill when your browser does not support WebVR natively. But, since from viewer 2.13, the following code is added to support webvr-polyfill, that makes your browser to support WebVR even it does not natively support WebVR yet.
// check if browser supports webVR1.1 natively, if not, load polyfill
avp.loadDependency('VRFrameData', 'webvr-polyfill.min.js', function() {})
Last, I have a simple running sample for WebVR at https://viewervr.herokuapp.com if you want to check the result, nothing more but just load the "'Autodesk.Viewing.WebVR" extension, if you run it on your mobile device, you will see the expected result.
Hope it helps.

Executable run from electron project isn't loading resources

I am making a electron application that launches an executable stored on my computer when run. If I run the exe by itself, it works correctly and loads all of the fonts. However, when run by the electron app, it opens, but non of the font files can be loaded. The exe is a compiled release project made in visual studio.
I tried putting the res folder into the same directory as index.html to no avail.
Code for index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script>
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release\\Ten.exe";
var parameters = ["test"];
child(exePath, parameters, function(err, data){
console.log(err);
console.log(data.toString());
})
</script>
</body>
</html>
Code for main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
Thanks!
Does your exe use a relative path to load the fonts? If so, either change the exe to be more flexible, or in your call to execFile() specify the optional 3rd arg to specify the desired working directory.
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release";
var exe = exePath + "\\Ten.exe";
var parameters = ["test"];
var options = {cwd:exePath};
child(exePath, parameters, options, function(err, data){
console.log(err);
console.log(data.toString());
});
If that doesn't work, my guess would be some kind of permissions problem. Is your electron app running as a different user to when you test the exe?