How to replace html href link with button - javascript

I have a HTML page that has Javascript in it (see below).
Within the HTML page there is a HTML code line that calls a Javascript function.
This works exactly as it should and looks like this :
hour
This code line calls from the last part of the below Javascript.
I wish to replace this code line with a button. How can I do this ?
Thank you
ps the Javascript is for use with dygraph and I did not write it. I know little about Javascript. I'm simply looking to replace the above single line of html with a button that does the same job or produce a button through other minimalistic change.
$(document).ready(function () {
var r = [ ];
var base_time = Date.parse("2014/03/05");
var num = 24 * 0.25 * 365;
for (var i = 0; i < num; i++) {
r.push([
new Date(base_time + i * 3600 * 1000),
i + 50 * (i % 60), // line
i * (num - i) * 4.0 / num // parabola
]);
}
var orig_range = [
r[0][0].valueOf(),
r[r.length - 1][0].valueOf()
];
// NEW CODE INSERTED - STARTS
var one_month_previous = new Date();
one_month_previous.setMonth(one_month_previous.getMonth() - 1);
var one_week_previous = new Date();
one_week_previous.setDate(one_week_previous.getDate()-7);
var three_days_previous = new Date();
three_days_previous.setDate(three_days_previous.getDate()-3);
var one_days_previous = new Date();
one_days_previous.setDate(one_days_previous.getDate()-1);
var twelve_hours_previous = new Date();
twelve_hours_previous.setHours(twelve_hours_previous.getHours() - 12);
// NEW CODE INSERTED - ENDS
g = new Dygraph(
document.getElementById("graphdiv3"),
"show_csv.php",
{
// NEW CODE INSERTED - STARTS
// dateWindow: [ Date.parse(one_month_previous) ,
// Date.parse(new Date()) ],
dateWindow: [
Date.parse(one_week_previous),
Date.parse(new Date())
],
// dateWindow: [ Date.parse(three_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(one_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(twelve_hours_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse("2014/03/01 12:00:00"),
// Date.parse("2014/03/31 12:00:00") ],
// NEW CODE INSERTED - ENDS
title: 'Temperature(°C) vs Time',
rollPeriod: 1,
showRoller: true,
xlabel: 'Time',
ylabel: 'Temperature (°C)',
legend: 'always',
labelsKMB: 'true',
labelsSeparateLines: 'true',
colors: [
"rgb(51,204,204)",
"#00DD55",
"rgb(255,100,100)",
"rgba(50,50,200,0.4)"
]
}
);
var desired_range = null;
function approach_range() {
if (!desired_range) return;
// go halfway there
var range = g.xAxisRange();
if (Math.abs(desired_range[0] - range[0]) < 60 &&
Math.abs(desired_range[1] - range[1]) < 60) {
g.updateOptions({dateWindow: desired_range});
// (do not set another timeout.)
} else {
var new_range;
new_range = [
0.5 * (desired_range[0] + range[0]),
0.5 * (desired_range[1] + range[1])
];
g.updateOptions({dateWindow: new_range});
animate();
}
}
function animate() {
setTimeout(approach_range, 50);
}
var zoom = function(res) {
var w = g.xAxisRange();
desired_range = [ w[0], w[0] + res * 1000 ];
animate();
}
var reset = function() {
desired_range = orig_range;
animate();
}
var pan = function(dir) {
var w = g.xAxisRange();
var scale = w[1] - w[0];
var amount = scale * 0.25 * dir;
desired_range = [
w[0] + amount,
w[1] + amount
];
animate();
}
document.getElementById('hour').onclick = function() { zoom(3600); };
document.getElementById('day').onclick = function() { zoom(86400); };
document.getElementById('week').onclick = function() { zoom(604800); };
document.getElementById('month').onclick = function() { zoom(30 * 86400); };
document.getElementById('full').onclick = function() { reset(); };
document.getElementById('left').onclick = function() { pan(-1); };
document.getElementById('right').onclick = function() { pan(+1); };
});

if you want that the link looks like a button, then you can style the link with css that he looks like a button.
http://www.usabilitypost.com/2012/01/10/pressed-button-state-with-css3/

Just style it your way now!=)
(IE optimized:)
not sure if this is right tho.
<a href="#">
<button id="hour">Hour</button>
</a>
Normal button
<button id="hour">Hour</button>
form method:
<form action="#">
<input type="submit" value="submit">
</form>

Dude encapsulate the javascript inside a function first
//
function foo()
{
$(document).ready(function () {
var r = [ ];
var base_time = Date.parse("2014/03/05");
var num = 24 * 0.25 * 365;
for (var i = 0; i < num; i++) {
r.push([ new Date(base_time + i * 3600 * 1000),
i + 50 * (i % 60), // line
i * (num - i) * 4.0 / num // parabola
]);
}
var orig_range = [ r[0][0].valueOf(), r[r.length - 1][0].valueOf() ];
// NEW CODE INSERTED - STARTS
var one_month_previous = new Date();
one_month_previous.setMonth(one_month_previous.getMonth() - 1);
var one_week_previous = new Date();
one_week_previous.setDate(one_week_previous.getDate()-7);
var three_days_previous = new Date();
three_days_previous.setDate(three_days_previous.getDate()-3);
var one_days_previous = new Date();
one_days_previous.setDate(one_days_previous.getDate()-1);
var twelve_hours_previous = new Date();
twelve_hours_previous.setHours(twelve_hours_previous.getHours() - 12);
// NEW CODE INSERTED - ENDS
g = new Dygraph(
document.getElementById("graphdiv3"),
"show_csv.php",
{
// NEW CODE INSERTED - STARTS
// dateWindow: [ Date.parse(one_month_previous) ,
// Date.parse(new Date()) ],
dateWindow: [ Date.parse(one_week_previous) ,
Date.parse(new Date()) ],
// dateWindow: [ Date.parse(three_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(one_days_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse(twelve_hours_previous) ,
// Date.parse(new Date()) ],
// dateWindow: [ Date.parse("2014/03/01 12:00:00"),
// Date.parse("2014/03/31 12:00:00") ],
// NEW CODE INSERTED - ENDS
title: 'Temperature(°C) vs Time',
rollPeriod: 1,
showRoller: true,
xlabel: 'Time',
ylabel: 'Temperature (°C)',
legend: 'always',
labelsKMB: 'true',
labelsSeparateLines: 'true',
colors: [
"rgb(51,204,204)",
"#00DD55",
"rgb(255,100,100)",
"rgba(50,50,200,0.4)"]
}
);
var desired_range = null;
function approach_range() {
if (!desired_range) return;
// go halfway there
var range = g.xAxisRange();
if (Math.abs(desired_range[0] - range[0]) < 60 &&
Math.abs(desired_range[1] - range[1]) < 60) {
g.updateOptions({dateWindow: desired_range});
// (do not set another timeout.)
} else {
var new_range;
new_range = [0.5 * (desired_range[0] + range[0]),
0.5 * (desired_range[1] + range[1])];
g.updateOptions({dateWindow: new_range});
animate();
}
}
function animate() {
setTimeout(approach_range, 50);
}
var zoom = function(res) {
var w = g.xAxisRange();
desired_range = [ w[0], w[0] + res * 1000 ];
animate();
}
var reset = function() {
desired_range = orig_range;
animate();
}
var pan = function(dir) {
var w = g.xAxisRange();
var scale = w[1] - w[0];
var amount = scale * 0.25 * dir;
desired_range = [ w[0] + amount, w[1] + amount ];
animate();
}
document.getElementById('hour').onclick = function() { zoom(3600); };
document.getElementById('day').onclick = function() { zoom(86400); };
document.getElementById('week').onclick = function() { zoom(604800); };
document.getElementById('month').onclick = function() { zoom(30 * 86400); };
document.getElementById('full').onclick = function() { reset(); };
document.getElementById('left').onclick = function() { pan(-1); };
document.getElementById('right').onclick = function() { pan(+1); };
}
);
}
//]]>
</script>
Now, call the function from the button
<button id="hour" onClick="foo()">Hour</button>
Edit: And for the document.ready() not being safe:
Is it safe to call $(document).ready() from inside a function?
Edit: Guys you are right, and i'm really sorry, I didn't see the whole question before answering.
user1062153 There is no need to do the extra work in javascript, you just have to give the id to the element you are using. Just add the
<button id="hour">Hour</button>
as Xatenev said. That should work fine..

Related

Chrome Dev tools doesn't show any leak, but Task Manager does until chrome crashes

So I have this quite CPU-consuming app: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880
It's a Canvas on which things are drawn (a lot).
HTML:
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<div id="chartdiv" style="width:100%; height:400px"></div>
JavaScript:
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Generate random data
var value = 100;
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 1000);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 50; i++) {
var newDate = new Date(firstDate);
newDate.setSeconds(newDate.getSeconds() + i);
value += (Math.random() < 0.5 ? 1 : -1) * Math.random() * 10;
chartData.push({
date: newDate.getTime(),
value: value
});
}
return chartData;
}
var data = generateChartData();
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
focusable: true,
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
scrollbarX:am5.Scrollbar.new(root, {orientation:"horizontal"})
}));
var easing = am5.ease.linear;
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
maxDeviation: 0.5,
groupData: false,
extraMax:0.1, // this adds some space in front
extraMin:-0.1, // this removes some space form th beginning so that the line would not be cut off
baseInterval: {
timeUnit: "second",
count: 1
},
renderer: am5xy.AxisRendererX.new(root, {
minGridDistance: 50
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Series 1",
xAxis: xAxis,
yAxis: yAxis,
valueYField: "value",
valueXField: "date",
tooltip: am5.Tooltip.new(root, {
pointerOrientation: "horizontal",
labelText: "{valueY}"
})
}));
series.data.setAll(data);
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
// Update data every second
setInterval(function () {
addData();
}, 100)
function addData() {
var lastDataItem = series.dataItems[series.dataItems.length - 1];
var lastValue = lastDataItem.get("valueY");
var newValue = value + ((Math.random() < 0.5 ? 1 : -1) * Math.random() * 5);
var lastDate = new Date(lastDataItem.get("valueX"));
var time = am5.time.add(new Date(lastDate), "second", 1).getTime();
series.data.removeIndex(0);
series.data.push({
date: time,
value: newValue
})
var newDataItem = series.dataItems[series.dataItems.length - 1];
newDataItem.animate({
key: "valueYWorking",
to: newValue,
from: lastValue,
duration: 600,
easing: easing
});
var animation = newDataItem.animate({
key: "locationX",
to: 0.5,
from: -0.5,
duration: 600
});
if (animation) {
var tooltip = xAxis.get("tooltip");
if (tooltip && !tooltip.isHidden()) {
animation.events.on("stopped", function () {
xAxis.updateTooltip();
})
}
}
}
setTimeout(function(){
xAxis.zoom(0.5, 1)
}, 1500)
After some time of running it, all Chromium browsers crash. Even though Dev tools does not show any memory leak - number of listeners, nodes and heap size remains the same (the heap might increase a bit initially but then stabilizes). But the task manager shows memory growing. Important thing - the browser window must be focused. The strange thing is that if I zoom-out the chart using scrollbar or resize window or close and open the tab, the memory could drop to a normal level. This thing happens both with dev tools opened and closed.
This does not happen on Firefox, so I believe it's some browser issue. Appreciate for any insights.
So we found out that this is indeed a Chromium issue, calling setTransform on a context (if nothing else is done) results to leak (which is not visible when profiling) and a crash. We reported it as a bug and hopefully it will be fixed. Meanwhile we are working on a workaround to avoid this situation.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function loop() {
requestAnimationFrame(() => {
loop();
for (var j = 0; j < 10000; ++j) {
context.setTransform(0.5, 1, 1, 0.5, 1, 1);
}
});
}
loop();

amCharts Live Data -- adding multiple series

Disclaimer: I am still learning some of the basics and I am still learning proper terminology.
I am trying to use an example of amCharts with live data and add another series into the chart. My goal is to have a single chart with two series/lines streaming data.
The basic example I am working from is here:
https://codepen.io/team/amcharts/pen/MGVbNV
I have managed to get two line series working, however its extremely clunky at the moment.
Here is where I am at:
am4core.useTheme(am4themes_animated);
am4core.useTheme(am4themes_dark);
var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.hiddenState.properties.opacity = 0;
chart.padding(0, 0, 0, 0);
chart.zoomOutButton.disabled = true;
var data = [];
var upstream = 10;
var i = 0;
for (i = 0; i <= 30; i++) {
upstream -= Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({ date: new Date().setSeconds(i - 30), Upstream: upstream });
}
var downstream = 10;
var j = 0;
for (j = 0; j <= 30; j++) {
downstream -= Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({ date: new Date().setSeconds(j - 30), value: downstream });
}
chart.data = data;
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.renderer.minGridDistance = 30;
dateAxis.dateFormats.setKey("second", "ss");
dateAxis.periodChangeDateFormats.setKey("second", "[bold]h:mm a");
dateAxis.periodChangeDateFormats.setKey("minute", "[bold]h:mm a");
dateAxis.periodChangeDateFormats.setKey("hour", "[bold]h:mm a");
dateAxis.renderer.inside = true;
dateAxis.renderer.axisFills.template.disabled = true;
dateAxis.renderer.ticks.template.disabled = true;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
valueAxis.interpolationDuration = 500;
valueAxis.rangeChangeDuration = 500;
valueAxis.renderer.inside = true;
valueAxis.renderer.minLabelPosition = 0.05;
valueAxis.renderer.maxLabelPosition = 0.95;
valueAxis.renderer.axisFills.template.disabled = true;
valueAxis.renderer.ticks.template.disabled = true;
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.dateX = "date";
series1.dataFields.valueY = "Upstream";
series1.interpolationDuration = 500;
series1.defaultState.transitionDuration = 0;
series1.tensionX = 0.8;
var series2 = chart.series.push(new am4charts.LineSeries());
series2.dataFields.dateX = "date";
series2.dataFields.valueY = "Downstream";
series2.interpolationDuration = 500;
series2.defaultState.transitionDuration = 0;
series2.tensionX = 0.8;
chart.events.on("datavalidated", function () {
dateAxis.zoom({ start: 1 / 15, end: 1.2 }, false, true);
});
dateAxis.interpolationDuration = 500;
dateAxis.rangeChangeDuration = 500;
document.addEventListener("visibilitychange", function() {
if (document.hidden) {
if (interval) {
clearInterval(interval);
}
}
else {
startInterval();
}
}, false);
// add data
var interval;
function startInterval() {
interval = setInterval(function() {
upstream =
upstream + Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 5);
var lastdataItem = series1.dataItems.getIndex(series1.dataItems.length - 1);
chart.addData(
{ date: new Date(lastdataItem.dateX.getTime() + 1000), Upstream: upstream },
1
);
downstream =
downstream + Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 1);
var lastdataItem = series2.dataItems.getIndex(series2.dataItems.length - 1);
chart.addData(
{ date: new Date(lastdataItem.dateX.getTime() + 1000), Downstream: downstream },
1
);
}, 1000);
}
startInterval();
// all the below is optional, makes some fancy effects
// gradient fill of the series
series1.fillOpacity = 1;
var gradient = new am4core.LinearGradient();
gradient.addColor(chart.colors.getIndex(0), 0.2);
gradient.addColor(chart.colors.getIndex(0), 0);
series1.fill = gradient;
// this makes date axis labels to fade out
dateAxis.renderer.labels.template.adapter.add("fillOpacity", function (fillOpacity, target) {
var dataItem = target.dataItem;
return dataItem.position;
})
// need to set this, otherwise fillOpacity is not changed and not set
dateAxis.events.on("validated", function () {
am4core.iter.each(dateAxis.renderer.labels.iterator(), function (label) {
label.fillOpacity = label.fillOpacity;
})
})
// this makes date axis labels which are at equal minutes to be rotated
dateAxis.renderer.labels.template.adapter.add("rotation", function (rotation, target) {
var dataItem = target.dataItem;
if (dataItem.date.getTime() == am4core.time.round(new Date(dataItem.date.getTime()), "minute").getTime()) {
target.verticalCenter = "middle";
target.horizontalCenter = "left";
return -90;
}
else {
target.verticalCenter = "bottom";
target.horizontalCenter = "middle";
return 0;
}
})
// bullet at the front of the line
var bullet = series1.createChild(am4charts.CircleBullet);
bullet.circle.radius = 5;
bullet.fillOpacity = 1;
bullet.fill = chart.colors.getIndex(0);
bullet.isMeasured = false;
series1.events.on("validated", function() {
bullet.moveTo(series1.dataItems.last.point);
bullet.validatePosition();
});
Any insight and help on getting this to be smoother? I think I need to do something with SetInterval() or combine functions somehow.

Rendering an iframe onto an AR marker using CSS3DRenderer and jsartoolkit

I would like to be able to overlay a html iframe on top of an augmented reality marker, however I cannot get the CSS3DRenderer to show the same result as the WebGLRenderer and I'm not sure where I'm going wrong.
The WebGL renders perfectly, with the mesh following the marker and it's all magic, the CSS3DRenderer however centers the iframe in the middle of the video, inversed and unscaled, and it rotates in the opposite direction.
Thanks to three.js and artoolkit, here is some test code using video input and both renderers.
new Promise(function(resolve,reject) {
var source = document.createElement('video');
source.autoplay = true;
source.playsinline = true;
source.controls = false;
source.loop = true;
source.onplay = function(event) {
resolve(source);
}
source.src = 'data/output_4.ogg';
document.body.appendChild(source);
}).then(function(source) {
var scene = new THREE.Scene();
var camera = new THREE.Camera();
camera.matrixAutoUpdate = false;
scene.add(camera);
var material = new THREE.MeshNormalMaterial({
transparent : true,
opacity : 0.5,
side : THREE.DoubleSide
});
var geometry = new THREE.PlaneGeometry(1,1);
var mesh = new THREE.Mesh(geometry,material);
// mesh.matrixAutoUpdate = false;
scene.add(mesh);
var renderer = new THREE.WebGLRenderer({
antialias : true,
alpha : true
});
renderer.setSize(source.videoWidth,source.videoHeight);
renderer.setClearColor(new THREE.Color('lightgrey'),0);
document.body.appendChild(renderer.domElement);
/*\
cssRenderer
\*/
var cssRenderer = new THREE.CSS3DRenderer();
cssRenderer.setSize(source.videoWidth,source.videoHeight);
var cssScene = new THREE.Scene();
var iframe = document.createElement("iframe");
iframe.src = "/data/index.html";
iframe.style.background = "rgb(0,0,0)";
var iframe3D = new THREE.CSS3DObject(iframe);
// iframe3D.matrixAutoUpdate = false;
cssScene.add(iframe3D);
document.body.appendChild(cssRenderer.domElement);
/*\
arController
\*/
var cameraParameters = new ARCameraParam();
var arController = null;
cameraParameters.onload = function() {
arController = new ARController(source.videoWidth,source.videoHeight,cameraParameters);
arController.addEventListener("getMarker",function(event) {
var modelViewMatrix = new THREE.Matrix4().fromArray(event.data.matrix);
camera.matrix.getInverse(modelViewMatrix);
// mesh.matrix.copy(modelViewMatrix);
// iframe3D.matrix.copy(modelViewMatrix);
});
var cameraViewMatrix = new THREE.Matrix4().fromArray(arController.getCameraMatrix());
camera.projectionMatrix.copy(cameraViewMatrix);
}
cameraParameters.load("data/camera_para.dat");
/*\
animate
\*/
requestAnimationFrame(function animate() {
requestAnimationFrame(animate);
if (!arController) {
return;
}
arController.process(source);
renderer.render(scene,camera);
cssRenderer.render(cssScene,camera);
});
});
I had hoped that rotating the camera instead of the object would provide a solution, alas. It's as if I was missing out some matrix transformation that needs to be applied.
Perhaps there was something with the fov parameters of the camera, or maybe the transform matrix was getting overwritten, but anyway I couldn't locate the problem. So here's an alternative that doesn't use CSS3DRenderer, or THREE.js.
Essentially we can use the coordinates from the marker data itself to create a projection matrix. Many, many thanks to this post which provided most of the code I needed.
function adjugate(m) { // Compute the adjugate of m
return [
m[4]*m[8]-m[7]*m[5],m[7]*m[2]-m[1]*m[8],m[1]*m[5]-m[4]*m[2],
m[6]*m[5]-m[3]*m[8],m[0]*m[8]-m[6]*m[2],m[3]*m[2]-m[0]*m[5],
m[3]*m[7]-m[6]*m[4],m[6]*m[1]-m[0]*m[7],m[0]*m[4]-m[3]*m[1]
];
}
function multiply(a,b) { // multiply two matrices
a = [
a[0],a[3],a[6],
a[1],a[4],a[7],
a[2],a[5],a[8]
];
b = [
b[0],b[3],b[6],
b[1],b[4],b[7],
b[2],b[5],b[8]
];
var m = Array(9);
for (var i = 0; i != 3; ++i) {
for (var j = 0; j != 3; ++j) {
var mij = 0;
for (var k = 0; k != 3; ++k) {
mij += a[3*i + k]*b[3*k + j];
}
m[3*i + j] = mij;
}
}
return [
m[0],m[3],m[6],
m[1],m[4],m[7],
m[2],m[5],m[8]
];
}
function apply(m,v) { // multiply matrix and vector
return [
m[0]*v[0] + m[3]*v[1] + m[6]*v[2],
m[1]*v[0] + m[4]*v[1] + m[7]*v[2],
m[2]*v[0] + m[5]*v[1] + m[8]*v[2]
];
}
//
var iframe = document.createElement("iframe");
iframe.src = "data/index.html";
iframe.style.position = "absolute";
iframe.style.left = "0";
iframe.style.top = "0";
iframe.style.transformOrigin = "0 0";
document.querySelector("main").appendChild(iframe);
var s = [
0,0,1,
iframe.offsetWidth,0,1,
0,iframe.offsetHeight,1
];
var v = apply(adjugate(s),[iframe.offsetWidth,iframe.offsetHeight,1]);
s = multiply(s,[
v[0], 0, 0,
0, v[1], 0,
0, 0, v[2]
]);
arController.addEventListener("getMarker",function(event) {
if (event.data.marker.id === marker) {
var d = [
event.data.marker.vertex[(4 - event.data.marker.dir) % 4][0],event.data.marker.vertex[(4 - event.data.marker.dir) % 4][1],1,
event.data.marker.vertex[(5 - event.data.marker.dir) % 4][0],event.data.marker.vertex[(5 - event.data.marker.dir) % 4][1],1,
event.data.marker.vertex[(7 - event.data.marker.dir) % 4][0],event.data.marker.vertex[(7 - event.data.marker.dir) % 4][1],1
];
var v = apply(adjugate(d),[event.data.marker.vertex[(6 - event.data.marker.dir) % 4][0],event.data.marker.vertex[(6 - event.data.marker.dir) % 4][1],1]);
d = multiply(d,[
v[0],0,0,
0,v[1],0,
0,0,v[2]
]);
var t = multiply(d,adjugate(s));
for (i = 0; i < 9; ++i) {
t[i] = t[i] / t[8];
t[i] = Math.abs(t[i]) < Number.EPSILON ? 0 : t[i];
}
t = [
t[0],t[1],0,t[2],
t[3],t[4],0,t[5],
0,0,1,0,
t[6],t[7],0,t[8]
];
iframe.style.transform = "matrix3d(" + t.join(", ") + ")";
} else {
// mesh.visible = false;
}
});
Might be an answer 4 years overdue, but it might be useful for somebody.
I've created an alternative solution.
You can check it here: https://github.com/jonathanneels/QrA
In essence;
QrA uses tilt-js to simulate 3D-effects (parallax) and AR.js a-box as the startobject.
The iframe gets pushed by the tilt.js functions and the AR cube's .position, .scale and .rotation is used as reference.
Enjoy!

How to reverse the direction of applying texture in the object CylinderGeometry?

How to reverse the direction of applying texture in the object CylinderGeometry?
var obj = new THREE.Mesh(
new THREE.CylinderGeometry(20, 15, 1, 20),
new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the correct
);
Thank you in advance for your help :)
This function works:
var invertTextureOnCylinderGeometry = function(obj) {
var faceVertexes = obj.geometry.faceVertexUvs[0];
var faceVertexesLength = faceVertexes.length;
var divisionT = 1 / (faceVertexesLength * 0.25);
faceVertexes.map(function(face, index) {
if (index < 0.5*faceVertexesLength) {
var thisIndexDivision = [
Math.floor(index/2) * divisionT,
Math.ceil((index+divisionT)/2) * divisionT
];
if (index % 2) {
face[0].set(1, thisIndexDivision[0]);
face[1].set(1, thisIndexDivision[1]);
face[2].set(0, thisIndexDivision[1]);
} else {
face[0].set(0, thisIndexDivision[0]);
face[1].set(1, thisIndexDivision[0]);
face[2].set(0, thisIndexDivision[1]);
}
}
});
obj.geometry.uvsNeedUpdate = true;
};

JavaScript Auto Updating Graph

Hello StackOverFlow I hate to bother you guys, but I really struggle with JavaScript and I am looking for a way to simply monitor this Javascript so that the Y variable is grabbed from one of my php files.
Example: http://foo.com/bar.php so I can have a live graph of my user data
Thank you so much for the help I appreciate it
The following code is the example JavaScript code which generates random data I guess.
/* Lines with autodrowing */
$(function () {
// we use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 200;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i)
res.push([i, data[i]])
return res;
}
// setup control widget
var updateInterval = 1000;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
if (updateInterval > 2000)
updateInterval = 2000;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
yaxis: { min: 0, max: 100 },
xaxis: { min: 0, max: 100 },
colors: ["#aed267"],
series: {
lines: {
lineWidth: 2,
fill: true,
fillColor: { colors: [ { opacity: 0.4 }, { opacity: 0 } ] },
//"#dcecf9"
steps: false
}
}
};
var plot = $.plot($(".updating"), [ getRandomData() ], options);
function update() {
plot.setData([ getRandomData() ]);
// since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
I'm not sure of what your question is.
If you just want to get Y value from the serveur, do an ajax call :
var yVal;
$.ajax({
url:"/yourserv?action=getYValue",
success: function(data){
yVal = data;
}
});

Categories

Resources