Tiempo Real

TimeSeries plantilla con datos en tiempo real. Esta demo incluye la animación de la selección cuando llegan datos nuevos. Los propios datos son de una función, pero podría ser una devolución de llamada a un origen de datos remoto.

(function realtime_demo (container) {

var
 x = [],
 dataA = [],
 dataB = [],
 data = [[x, dataA], [x, dataB]],
 options, i, timesries;

// Mock Data:
 function sample(i) {
 x.push(i);
 dataA.push(Math.sin(i / 6) * (Math.random() + 1) / 2);
 dataB.push(Math.sin(i / 6 + Math.PI / 2) * (Math.random() + 1) / 2);
 }

// Initial Data:
 for (i = 0; i < 100; i++) {  sample(i);  } // Envision Timeseries Options  options = {  container : container,  data : {  detail : data,  summary : data  },  defaults : {  summary : {  config : {  handles : { show : false }  }  }  }  } // Render the timeseries  timeseries = new envision.templates.TimeSeries(options); // Method to get new data  // This could be part of an Ajax callback, a websocket callback,  // or streaming / long-polling data source.  function getNewData () {  i++; // Short circuit (no need to keep going! you get the idea)  if (i > 1000) return;

sample(i);
 animate(i);
 }

// Initial request for new data
 getNewData();

// Animate the new data
 function animate (i) {

var
 start = (new Date()).getTime(),
 length = 500, // 500ms animation length
 max = i - 1, // One new point comes in at a time
 min = i - 51, // Show 50 in the top
 offset = 0; // Animation frame offset

// Render animation frame
 (function frame () {

var
 time = (new Date()).getTime(),
 tick = Math.min(time - start, length),
 offset = (Math.sin(Math.PI * (tick) / length - Math.PI / 2) + 1) / 2;

// Draw the summary first
 timeseries.summary.draw(null, {
 xaxis : {
 min : 0,
 max : max + offset
 }
 });

// Trigger the select interaction.
 // Update the select region and draw the detail graph.
 timeseries.summary.trigger('select', {
 data : {
 x : {
 min : min + offset,
 max : max + offset
 }
 }
 });

if (tick < length) {
 setTimeout(frame, 20);
 } else {
 // Pretend new data comes in every second
 setTimeout(getNewData, 500);
 }
 })();
 }
 }
 )(document.getElementById("editor-render-0"));

TimeSeries

Tiempo de serie del gráfico de HTML5. Este utiliza la plantilla TimeSeries. Las plantillas proporcionan visualizaciones interactivas pre-construidas de juegos comunes. TimeSeries viene con soporte de zoom.


(function timeseries_demo (container) {

var options = {
 container : container,
 data : {
 detail : financeData.price,
 summary : financeData.price
 },
 // An initial selection
 selection : {
 data : {
 x : {
 min : 100,
 max : 200
 }
 }
 }
 };

return new envision.templates.TimeSeries(options);
}
)(document.getElementById("editor-render-0"));

Finanzas

Gráfico HTML5 financiero. Esta demo mustra la plantilla con los datos en el espacio de nombres global. En él se especifica una selección inicial y formateadores personalizados para las etiquetas del eje X y el seguimiento del ratón.


(function finance_demo (container) {

var
 summaryTicks = financeData.summaryTicks,
 options = {
 container : container,
 data : {
 price : financeData.price,
 volume : financeData.volume,
 summary : financeData.price
 },
 trackFormatter : function (o) {

var
 data = o.series.data,
 index = data[o.index][0],
 value;

value = summaryTicks[index].date + ': $' + summaryTicks[index].close + ", Vol: " + summaryTicks[index].volume;

return value;
 },
 xTickFormatter : function (index) {
 var date = new Date(financeData.summaryTicks[index].date);
 return date.getFullYear() + '';
 },
 // An initial selection

selection : {
 data : {
 x : {
 min : 100,
 max : 200
 }
 }
 }
 };

return new envision.templates.Finance(options);
}
)(document.getElementById("editor-render-0"));

Ajax

AJAX maneja la gráfica financiera. Esta demostración utiliza la misma plantilla de Finanzas que la anterior, pero con la diferencia de utilizar la devolución de llamada “interacción de selección” para gestionar los datos. En este caso el rango de selección sólo se dispara un solo GET, pero esto podría ser arbitrariamente complejo.


(function ajax_demo (container) {

// Get initial data
 $.getJSON(HSD_BASE + 'static/json/envision/ajax-demo-initial-data.json', function (initialData) {

var
 currentData = initialData,
 options, finance;

options = {
 container : container,
 data : {
 price : currentData.price,
 volume : currentData.volume,
 summary : currentData.summary
 },
 trackFormatter : function (o) {

var
 index = o.index,
 value;

value = currentData.data[index].date + ': $' + currentData.price[index][1] + ", Vol: " + currentData.volume[index][1];

return value;
 },
 // An initial selection
 selection : {
 data : {
 x : {
 min : 0,
 max : 250

}
 }
 },
 // Override some defaults.
 // Skip preprocessing to use flotr-formatted data.
 defaults : {
 volume : {
 skipPreprocess : true
 },
 price : {
 skipPreprocess : true
 },
 summary : {
 skipPreprocess : true,
 config : {
 xaxis : {
 // Set x ticks manually with defaults override:
 ticks : currentData.summaryTicks
 }
 }
 }
 }
 };

// Set the selection callback:
 //
 // This callback is applied after a selection action but
 // before the components are updated. This lets a developer
 // control the components configuration or data based upon
 // the area selected.

//
 // The only argument of the callback is the result of the
 // action — in this case a selection area in this case.
 // Desiging to the interface of the Component allows the
 // data handling to be entirely separate and arbitarily
 // complex.
 //
 options.selectionCallback = (function () {

var data = {
 initial : initialData,
 fetched : null
 };

// Helper for fetching high resolution data
 function fetchData (o) {
 $.getJSON(HSD_BASE + 'static/json/envision/ajax-demo-dynamic-data.json', function (fetchedData) {
 data.fetched = fetchedData;
 currentData = fetchedData;
 finance.price.options.data = data.fetched.price;
 finance.volume.options.data = data.fetched.volume;
 _.each(finance.selection.followers, function (follower) {
 follower.trigger('zoom', o);
 }, this);
 });
 }

// Selection callback:

return function (selection) {

if (finance) {
 var
 x = selection.data.x;

if (x.max !== null && Math.abs(x.max - x.min) < 250) {
 if (data.fetched) {

// Use high resolution data, if available
 finance.price.options.data = data.fetched.price;
 finance.volume.options.data = data.fetched.volume;
 currentData = data.fetched;
 } else {

// Fetch high resolution data
 fetchData(selection);
 }
 } else {

// Use low resolution data
 finance.price.options.data = data.initial.price;
 finance.volume.options.data = data.initial.volume;
 currentData = data.initial;
 }
 }
 }
 })();

finance = new envision.templates.Finance(options);
 });

}
)(document.getElementById("editor-render-0"));

Custom – Fractal

Una visualización hecha a la medida, la cual dibuja un fractal. En lugar de una plantilla, se utiliza la API de imaginar, e incluye una visualización, un componente, y una interacción para el zoom. El propio fractal se representa mediante un tipo de gráfico personalizado llamado flotr.


(function fractal_demo (container) {

Flotr.addType('fractal', {
 options: {
 show: false // => setting to true will show lines, false will hide
 },
 /**
 * Draws lines series in the canvas element.
 * @param {Object} series - Series with options.lines.show = true.
 */
 draw : function (options) {

if (!options.context.getImageData) return;

var
 context = options.context,
 width = options.width,
 height = options.height,
 range = options.data,
 xScale = options.xScale,
 yScale = options.yScale,
 xMin = range[0][0],
 xMax = range[1][0],
 yMin = range[0][1],
 yMax = range[1][1],
 xPMin = xScale(xMin),
 xPMax = xScale(xMax),
 yPMin = yScale(yMin),
 yPMax = yScale(yMax),
 // Scale bounds based upon initial data:
 minRe = (xMax - xMin) * (-xPMin) / (xPMax - xPMin) + xMin,
 maxRe = (xMax - xMin) * (-xPMin + width) / (xPMax - xPMin) + xMin,
 minIm = (yMax - yMin) * (-yPMin + height) / (yPMax - yPMin) + yMin,
 maxIm = (yMax - yMin) * (-yPMin) / (yPMax - yPMin) + yMin,
 reFactor = (maxRe - minRe) / (width - 1),

imFactor = (maxIm - minIm) / (height - 1),
 max = 50,
 image = context.getImageData(0, 0, width, height),
 data = image.data,
 row, column, n, index,
 c_r, c_i,
 z_r, z_i,
 z_r2, z_i2,
 inside, ratio;

for (row = 0; row < height; row++) {

c_i = maxIm - row * imFactor;

for (column = 0; column < width; column++) {

c_r = minRe + column * reFactor;
 z_r = c_r;
 z_i = c_i;
 inside = true;

for (n = 0; n < max; n++) {  z_r2 = z_r * z_r;  z_i2 = z_i * z_i;  if (z_r2 + z_i2 > 4) {
 inside = false;
 break;
 }

z_i = 2 * z_r * z_i + c_i;
 z_r = z_r2 - z_i2 + c_r;

}

index = row * width * 4 + column * 4;
 ratio = n / max;
 data[index + 3] = 255;
 if (!inside) {
 data[index + 0] = 255 - 255 * ratio;
 data[index + 1] = 255 - 255 * ratio;
 data[index + 2] = 255;
 } else {
 data[index + 2] = 80;
 }
 }
 }

context.putImageData(image, 0, 0);
 }
 });

var
 E = Flotr.EventAdapter,
 fractalOptions = {
 name : 'fractal',
 data : [[-2, 1.2], [1, -1.2]],
 config : {
 fractal : {
 show : true
 },
 selection : {
 mode : 'xy'
 }
 },
 skipPreprocess : true
 },
 vis, zoom, zoomConfig;

vis = new envision.Visualization();
 fractal = new envision.Component(fractalOptions);
 zoom = new envision.Interaction();

vis
 .add(fractal)
 .render(container);

zoom
 .group([fractal])
 .add(envision.actions.zoom, zoomConfig);
}
)(document.getElementById("editor-render-0"));

Cecy Martínez

Cecy Martínez

Jefa de contenido y editora en HTML5Fácil, NinjaCodeTV, Desveloperstv y Co funder de WaveCode.LA

2 comentarios en “Envision.js: Biblioteca para crear visualizaciones HTML5

  1. Que buena pagina tienen, tienen tanta información que nose por donde empezar a aprender. XD. Pero bueno, creo que empezare por aqui ya que algunas vez me pidieron hacer algo como esto.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Cerrar