HTML Canvas - Updating the canvas periodically - html

I have a canvas which I use to draw a plot periodically. I have a function that receives data periodically, and it parses the data and plots it on the canvas. For the plotting I use Chart.js.
But I am not able to update the plot periodically. I have confirmed that the data are received correctly and parsed, but the plot is not updating. It updates when I click the page, or if I minimize the browser and maximize it again. The plot would briefly appear and the next time update is called, the plot dissapears.
Here is my code. I am using Firefox.
function start ()
{
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/consoleappsample', 'my-protocol');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt)
{
ParseIncomingData(evt.data);
};
// when the connection is established, this method is called
ws.onopen = function ()
{
inc.innerHTML = 'Connected<br/>';
textPanel.style.background = "#00FF00";
};
// when the connection is closed, this method is called
ws.onclose = function ()
{
inc.innerHTML = 'Connection closed<br/>';
textPanel.style.background = "#FF0000";
}
var periodicFuncID = setInterval( function() { ws.send(1); }, 2000);
}
function ParseIncomingData(data)
{
var splitContents = data.split(',');
var inc = document.getElementById('incomming');
var xaxis = new Array();
var yaxis = new Array();
yaxis = splitContents;
var dataType = yaxis.shift();
var data;
for(var i=1; i<=yaxis.length; i++)
{
xaxis.push(i);
}
data =
{
labels : xaxis,
datasets : [
{
//fillColor : "rgba(135,206,250,0.5)",
fillColor : "rgba(0,0,0,0.4)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(255,165,0,1)",
pointStrokeColor : "#585858 ",
data : yaxis
}
]
}
var canvas= document.getElementById('Plot');
var ctx = canvas.getContext("2d");
var myLine = new Chart(ctx).Line(data);
}
window.onload = start;
Most of the code is unrelated to my problem but I just wanted to know if there is something wrong in the way I handle.
Thank you.

Related

Autodesk Forge Viewer Api Cannot load markups inside screenshot

Good day,
I am using the latest Autodesk forge viewer and I am trying to take a screenshot that also renders my markups. Right now my code takes a screenshot without any markups. Below is my viewer code. I am loading markups Core and markups Gui extensions. Notice the "takeSnapshot(viewer)" function inside onDocumentLoadSuccess(viewerDocument). The function is defined right before the initializer function.
function takeSnapshot(target){
$('#snipViewer').click( () => {
target.getScreenShot(1600, 920, (blobURL) => {
let snip = blobURL;
$('#sniplink').attr("href", snip);
$('#sniplink').html('Not Empty');
$('#sniplink').css({"background-image": `url(${blobURL})`});
});
});
}
//Autodesk Viewer Code
instance.data.showViewer = function showViewer(viewerAccessToken, viewerUrn){
localStorage.setItem("viewerAccessTokentoken", viewerAccessToken);
localStorage.setItem("viewerUrn", viewerUrn);
var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2',
getAccessToken: function(onTokenReady) {
var token = viewerAccessToken;
var timeInSeconds = 3600;
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
let htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
let startedCode = viewer.start();
viewer.setTheme("light-theme");
viewer.loadExtension("Autodesk.CustomDocumentBrowser").then(() => {
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.loadExtension("Autodesk.Viewing.MarkupsGui");
});
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
$("#loadingStatus").html("Failed to create a Viewer: WebGL not supported.");
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = `urn:` + viewerUrn;
var derivativeId = `urn:` + instance.derivativeUrn;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
takeSnapshot(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
$("#loadingStatus").html("Failed fetching Forge manifest.");
}
}
I have already read this article: https://forge.autodesk.com/blog/screenshot-markups
I have tried doing this method but the instructions are very unclear for me. <div style="width:49vw; height:100vh;display:inline-block;"><canvas id="snapshot" style="position:absolute;"></canvas><button onclick="snaphot();" style="position:absolute;">Snapshot!</button></div>
What is the canvas element here for? Am I supposed to renderToCanvas() when I load the markups extension inside the initialize function or in my screenshot function? Is there some way I can implement the renderToCanvas() without changing too much of what I already am using here? I am not an expert with the viewer API so please if you could help me it would be very much appreciated, I am a beginner please don't skip many steps.
Thank you very much!
Here's a bit more simplified logic for generating screenshots with markups in Forge Viewer, with a bit more explanation on why it needs to be done this way below:
function getViewerScreenshot(viewer) {
return new Promise(function (resolve, reject) {
const screenshot = new Image();
screenshot.onload = () => resolve(screenshot);
screenshot.onerror = err => reject(err);
viewer.getScreenShot(viewer.container.clientWidth, viewer.container.clientHeight, function (blobURL) {
screenshot.src = blobURL;
});
});
}
function addMarkupsToScreenshot(viewer, screenshot) {
return new Promise(function (resolve, reject) {
const markupCoreExt = viewer.getExtension('Autodesk.Viewing.MarkupsCore');
const canvas = document.createElement('canvas');
canvas.width = viewer.container.clientWidth;
canvas.height = viewer.container.clientHeight;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(screenshot, 0, 0, canvas.width, canvas.height);
markupCoreExt.renderToCanvas(context, function () {
resolve(canvas);
});
});
}
const screenshot = await getViewerScreenshot(viewer);
const canvas = await addMarkupsToScreenshot(viewer, screenshot);
const link = document.createElement('a');
link.href = canvas.toDataURL();
link.download = 'screenshot.png';
link.click();
Basically, the markups extension can only render its markups (and not the underlying 2D/3D scene) into an existing <canvas> element. That's why this is a multi-step process:
You render the underlying 2D/3D scene using viewer.getScreenShot, getting a blob URL that contains the screenshot image data
You create a new <canvas> element
You insert the screenshot into the canvas (in this case we create a new Image instance and render it into the canvas using context.drawImage)
You call the extension's renderToCanvas that will render the markups in the canvas on top of the screenshot image

HTML5 web audio controls

I have music play example http://www.smartjava.org/examples/webaudio/example3.html
And i need to show html5 audio player (with controls) for this song. How i can do it?
Javascript code from example below:
// create the audio context (chrome only for now)
// create the audio context (chrome only for now)
if (! window.AudioContext) {
if (! window.webkitAudioContext) {
alert('no audiocontext found');
}
window.AudioContext = window.webkitAudioContext;
}
var context = new AudioContext();
var audioBuffer;
var sourceNode;
var analyser;
var javascriptNode;
// get the context from the canvas to draw on
var ctx = $("#canvas").get()[0].getContext("2d");
// create a gradient for the fill. Note the strange
// offset, since the gradient is calculated based on
// the canvas, not the specific element we draw
var gradient = ctx.createLinearGradient(0,0,0,300);
gradient.addColorStop(1,'#000000');
gradient.addColorStop(0.75,'#ff0000');
gradient.addColorStop(0.25,'#ffff00');
gradient.addColorStop(0,'#ffffff');
// load the sound
setupAudioNodes();
loadSound("http://www.audiotreasure.com/mp3/Bengali/04_john/04_john_04.mp3");
function setupAudioNodes() {
// setup a javascript node
javascriptNode = context.createScriptProcessor(2048, 1, 1);
// connect to destination, else it isn't called
javascriptNode.connect(context.destination);
// setup a analyzer
analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0.3;
analyser.fftSize = 512;
// create a buffer source node
sourceNode = context.createBufferSource();
sourceNode.connect(analyser);
analyser.connect(javascriptNode);
sourceNode.connect(context.destination);
}
// load the specified sound
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// When loaded decode the data
request.onload = function() {
// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
playSound(buffer);
}, onError);
}
request.send();
}
function playSound(buffer) {
sourceNode.buffer = buffer;
sourceNode.start(0);
}
// log if an error occurs
function onError(e) {
console.log(e);
}
// when the javascript node is called
// we use information from the analyzer node
// to draw the volume
javascriptNode.onaudioprocess = function() {
// get the average for the first channel
var array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
// clear the current state
ctx.clearRect(0, 0, 1000, 325);
// set the fill style
ctx.fillStyle=gradient;
drawSpectrum(array);
}
function drawSpectrum(array) {
for ( var i = 0; i < (array.length); i++ ){
var value = array[i];
ctx.fillRect(i*5,325-value,3,325);
// console.log([i,value])
}
};
I think what you want is to use an audio tag for your source and use createMediaElementSource to pass the audio to webaudio for visualization.
Beware that createMediaElementSource checks for CORS access so you must have appropriate cross-origin access for this to work. (It looks like your audio source doesn't return the appropriate access headers for this to work.)

createPattern(backgroundImg, "repeat"); returns null

var backgroundImg = new Image(50, 50);
backgroundImg.src = "img/grass.png";
var backgroundPattern = screen.createPattern(backgroundImg, "repeat");
backgroundPattern is null. Why??
Because you need to give the image time to load. For this, use the onload handler on the Image instance. Note that this is asynchronous so you need to have that in mind for the rest of the code:
var backgroundPattern;
var backgroundImg = new Image(50, 50);
backgroundImg.onload = function() {
// provided screen holds the 2D context of the canvas:
backgroundPattern = screen.createPattern(this, "repeat");
// execute next part of your code from here...
// next();
};
backgroundImg.src = "img/grass.png";

How to save a completed polygon points leaflet.draw to mysql table

I would like to use leaflet.draw to create outlines of regions. I have managed to get this working ok: https://www.mapbox.com/mapbox.js/example/v1.0.0/leaflet-draw/
Now I'd like to save the data for each polygon to a mysql table. Am a little stuck on how I would go about exporting the data and the format I should be doing it in.
If possible I'd like to pull the data back into a mapbox/leaflet map in the future so guess something like geojson would be good.
So you could use draw:created to capture the layer, convert it to geojson then stringify it to save in your database. I've only done this once and it was dirty but worked.
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
If you want to collect the coordinates, you can do it this way:
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
// Process them any way you want and save to DB
...
});
var getShapes = function(drawnItems) {
var shapes = [];
drawnItems.eachLayer(function(layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes.push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes.push([layer.getLatLng()]);
}
});
return shapes;
};
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
// restore
L.geoJSON(JSON.parse(shape_for_db)).addTo(mymap);
#Michael Evans method should work if you want to use GeoJSON.
If you want to save LatLngs points for each shape you could do something like this:
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var latLngs;
if (type === 'circle') {
latLngs = layer.getLatLng();
}
else
latLngs = layer.getLatLngs(); // Returns an array of the points in the path.
// process latLngs as you see fit and then save
}
Don't forget the radius of the circle
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()],layer.getRadius())
}
PS that statement may not get the proper formatting but you see the point. (Or rather the radius as well as the point ;-)
Get shares as associative array + circle radius
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('Call Point!');
}
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
console.log("shapes",shapes);
});
var getShapes = function (drawnItems) {
var shapes = [];
shapes["polyline"] = [];
shapes["circle"] = [];
shapes["marker"] = [];
drawnItems.eachLayer(function (layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes["polyline"].push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes["circle"].push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes["marker"].push([layer.getLatLng()],layer.getRadius());
}
});
return shapes;
};
For me it worked this:
map.on(L.Draw.Event.CREATED, function (e) {
map.addLayer(e.layer);
var points = e.layer.getLatLngs();
puncte1=points.join(',');
puncte1=puncte1.toString();
//puncte1 = puncte1.replace(/[{}]/g, '');
puncte1=points.join(',').match(/([\d\.]+)/g).join(',')
//this is the field where u want to add the coordinates
$('#geo').val(puncte1);
});
For me it worked this:
after get coordinates send to php file with ajax then save to db
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a polygon!';
var drawControl = new L.Control.Draw({
position: 'topright',
draw: {
polyline: true,
polygon: true,
circle: true,
marker: true
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('');
}
drawnItems.addLayer(layer);
shape_for_db = layer.getLatLngs();
SEND TO PHP FILE enter code hereWITH AJAX
var form_data = new FormData();
form_data.append("shape_for_db",shape_for_db);
form_data.append("name", $('#nameCordinate').val());
$.ajax({
url: 'assets/map_create.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
var tmp = php_script_response.split(',');
alert(tmp );
}
});
});
map.on(L.Draw.Event.EDITED, function (e) {
var layers = e.layers;
var countOfEditedLayers = 0;
layers.eachLayer(function (layer) {
countOfEditedLayers++;
});
console.log("Edited " + countOfEditedLayers + " layers");
});
L.DomUtil.get('changeColor').onclick = function () {
drawControl.setDrawingOptions({rectangle: {shapeOptions: {color: '#004a80'}}});
};

How to initialize a google maps on pageinit without repeatingly loading the google map api script

I would like to be able to load the Google.maps API only once for alle my pages.
Then i would like to be able to use geolocation or loading a map into a page anywhere on my web app.
The problem is that I cant figure out to seperate API loading and map initialization.
Which means i need to load the API each time I create a map.
I have referenced most of my code further down in the post but i suppose the following code is the problem.That piece of code takes care of the API Loading but at the same time it takes care of setting the initialize() function as a callback function and calling it.
var script = document.createElement("script");
script.type = "text/javascript";
script.src ="http://maps.googleapis.com/maps/api/js?key=mykey&sensor=false&callback=initialize";
document.body.appendChild(script);
How do i load the api once, lets say in the header, and then create a new map each time I go to specific page. WIthout loading the maps API again. (Note that im using Jquery mobile so my header only gets loaded one time for a session.)
I get this error:
Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
Ii would like to tell you my setup.
-Im using Google Map APi v3
-I'm loading the API dynamically after the page has loaded.
-I'm using Jquery mobile, which means the page with google maps only gets partially reloaded when you visit it.
-Im using google maps for two things to show the map and for geolocation.
-I'm using the Google map api on several pages.
Im interacting with the map in 3 different places: In a header javascript see code below
A header javascript
A javascript in the body
The DIV in the body that holds the map.
Here is my code for the javascript that handles loading the API, showing the map, markers etc:
<script>
$('.error').hide();
//search criterias
var radius;
var timerange;
var type;
//user position variables
var userposition = false;
var mylatitudedegree = "=55.698";
var mylongitudedegree = "=12.579";
//map variables
var mapready = false;
var map;
var bound;
var markersArray = [];
//array for keeping track of the markers
var markercenter;
//hack
var pageinit = 0;
var initializer = 0;
var triggersearch = 0;
var loadscripts = 0;
var isgooglemapsloaded = false;
$( '#soegsagside' ).live( 'pageinit',function(event)
{
pageinit++;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, function(error) {
alert('Din location er ikke tilgængelig! Error code: ' + error.code);
userposition = false;
}, {
maximumAge : 60000,
timeout : 10000,
enableHighAccuracy : true
});
}
else {
alert("Din browser tillader ikke, at vise din lokation!");
userposition = false;
}
loadScript();
$("#search_filter_button").click(function() {
//hide the "skal udfyldes" labels
$('.error').hide();
// validate and process form here
radius = $("select#choose_radius_select").val();
if (radius == "vælg") {
$("label#radius_error").show();
$("select#choose_radius_select").focus();
return false;
}
timerange = $("select#choose_timerange_select").val();
if (timerange == "vælg") {
$("label#timerange_error").show();
$("select#choose_timerange_select").focus();
return false;
}
type = $("select#vælg_type").val();
if (type == "vælg") {
$("label#select_type_error").show();
$("select#vælg_type").focus();
return false;
}
//------------------post to php script ---------------
var dataString = 'radius=' + radius + '&timerange=' + timerange + '&type=' + type + '&mylatitudedegree=' + mylatitudedegree + '&mylongitudedegree=' + mylongitudedegree;
$.ajax({
type : "POST",
url : "soegsagDB.php",
data : dataString,
success : function(data) {
$('#søgeresultater').html(data);
$('#søgeresultater').trigger('create');
clearOverlays();
createtaskmarkers();
findCenterOfMarkers();
if (userposition) {
usergeoposition = new google.maps.LatLng(mylatitudedegree, mylongitudedegree);
map.setCenter(usergeoposition);
createuserposition(usergeoposition);
} else {
map.setCenter(markercenter);
}
expandMapBoundForMarkers()
}
});
//end of post search query to server
return false;
});
//end of click seach button
});
//end of page ready
function setPosition(position) {
userposition = true;
myposition = position.coords;
mylatitudedegree = position.coords.latitude;
mylongitudedegree = position.coords.longitude;
var milli = new Date();
}
//function for clearing the markerArray
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
//Function for initializing the map, which is called when the map is created
function initialize() {
initializer++;
bound = new google.maps.LatLngBounds();
var mapOptions = {
zoom : 13,
center : new google.maps.LatLng(55, 12),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
//Create a map
map = new google.maps.Map(document.getElementById("map"), mapOptions);
mapready = true;
$("#search_filter_button").trigger('click');//Trigger click on the search button
triggersearch++;
}
//create user positio marker
function createuserposition(usergeoposition) {
var userPositionMarker = new google.maps.Marker({
position : usergeoposition,
map : map,
title : "Din position",
});
markersArray.push(userPositionMarker);
}
function createtaskmarkers() {
//Create the markers of the tasks
//1. find the task <li> that contain the data and loop through each one
//2. for each task collect the dato into variables and create markers and infowindows
//3. calculate center of point
//4. extendt map area to contain all points
var data = $.map($('li'), function(element) {
if (element.hasAttribute("data-latitude")) {
var tempPos = new google.maps.LatLng($(element).attr('data-latitude'), $(element).attr('data-longitude'));
var link = $(element).attr('data-link');
var title = $(element).attr('data-title');
var type = $(element).attr('data-type');
var date = $(element).attr('data-date');
tempMarker = new google.maps.Marker({
position : tempPos,
map : map,
title : title,
});
tempMarker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var tempContentString = '<div style="width: 200px; height: 100px;">' + date + '<br></br>' + '<b>' + type + ' , ' + title + '</b>' + '</div>';
//Create infowindow
var tempInfowindow = new google.maps.InfoWindow({
content : tempContentString
});
//add market to markerArray
markersArray.push(tempMarker);
//Create event with infowindow
google.maps.event.addListener(tempMarker, 'click', function() {
tempInfowindow.open(map, this);
});
}
});
}
function findCenterOfMarkers() {
//calculate center of markers and change mapcenter to that
var sumlatitude = 0;
var sumlongitude = 0;
for ( position = 0; position < markersArray.length; position++) {
sumlatitude += markersArray[position].getPosition().lat();
sumlongitude += markersArray[position].getPosition().lat();
}
avglatitude = sumlatitude / markersArray.length;
avglongitude = sumlongitude / markersArray.length;
markercenter = new google.maps.LatLng(avglatitude, avglongitude);
}
function expandMapBoundForMarkers() {
//Extend bounds for map to fit all markers into map
for (var i in markersArray) {
bound.extend(markersArray[i].getPosition());
}
map.fitBounds(bound);
}
//loads the google maps api with KEY and appends the script to the document body
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyC8wZ6RmFySy0DnWvrUaA-2OJqcM1_AOIc&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
The only thing in the body of the page that has to do with the maps. Is the DIV that the map is loaded into.
<div id="map" style="width: 80%; height: 280px; margin: auto; background-color: gray">Kortet loader, vent venligst.</div> <!--alternative for full screen style="position:absolute;top:30px;bottom:50px;left:0;right:0;"-->
The API is also loaded in a common header script. Because I in general need to load it on other pages.
<script src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script type="text/javascript">
$(document).ready( function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=mynamespace.init_google_maps";
document.body.appendChild(script);
$(document).bind('pageinit', function() {
//do stuff here that happens each time a new page is loaded
});
});
});
</script>
the api is loaded once inside .ready(). you can create a new map in the callback that was passed to .bind() which is called each time a new page loads or is inserted. you can initialize the map inside mynamespace. mynamespace is a .js file included on the page