Database Reference
In-Depth Information
elements can still be used to render and style static elements, such as the
axes, and then the SVG elements are positioned over the Canvas elements.
Even this method has limitations that prevent truly rapid updates because
the entire canvas has to be rendered on each frame. For very simple charts,
a high-speed update mechanism works by simply updating the leftmost
section of the canvas. To do this, first initialize the canvas element for draw.
In this case, the canvas is called canvas1 in the HTML document:
var size = 80,width = 960,height = 120;
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var w = width/size;
var y =
d3.scale.linear().domain([0,200]).range([2,height-4]);
Because the segments are relatively short, the easiest way to draw the strip
chart is to use linear interpolation from the previous point to the current
point. This allows the update step to be exceedingly simple. The context
simply draws a straight line from the ( width-w,lastY) point to the
(width,newY) point to produce a line segment:
var lastY;
$(document).on('data:unsigned',function(event,newY) {
if(lastY != undefined) {
shiftCanvasLeft();
ctx.beginPath();
ctx.moveTo(width-w,y(lastY));
ctx.lineTo(width,y(newY));
ctx.stroke();
}
lastY = newY;
});
Note that before the line segment is drawn, the shiftCanvasLeft
function is called. This function takes a snapshot of the current canvas and
then redraws it w pixels to the left:
function shiftCanvasLeft() {
var img = ctx.getImageData(0,0,width,height);
Search WWH ::




Custom Search