New canvas clipping functions
Written by Richard Heyes, RGraph author, on 28th March 2022
Following on from the previous dual-color Line chart
demo
here's another example of that sort of chart. The
difference with
this one is that it uses two new functions that have been
added to RGraph: RGraph.ClipTo.start
and
RGraph.clipTo.end
These functions will be
available from version 6.07 and make clipping the canvas
easier. The documentation for them will be part of
the API docs (it will
only be there after version 6.07 has been released).
The beforedraw
and draw
RGraph events
are still used to set up and remove clipping, but the RGraph
functions make doing this far clearer and easier to
understand.
View the example on codepen.io
// This is the first chart and draws the green, // top half of the chart line1 = new RGraph.Line({ id: 'cvs', data: data = [ 4,8,6,3,2,4,-5,-4,5,6,-1,-9,1,2,-3,-5,-7,-4,-2,-2,6,2,3,4, 4,8,6,2,3,5,1,4,9,5,6,4,3,8,7,5,6,4,5,1,2,3,4,6 ], options: { textSize: 15, xaxisPosition: 'center', yaxis: false, backgroundGridHlinesCount: 10, backgroundGridVlines: false, backgroundGridBorder: false, shadow: false, linewidth: 0.5, colors: ['green'], filled: true, filledColors:['rgba(0,255,128,0.25)'], marginInner: 15, spline: true, xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], xaxisTickmarksCount: 12 } }).on('beforedraw', function (obj) { // This is the new function that makes clipping the // canvas much easier. It can take a multitude of different // arguments. In this case, it simply clips to the top half // of the canvas (and then the other chart clips to the // bottom half). You can read about all of the different // ways that you can call this function in the API documentation // ( https://www.rgraph.net/canvas/api.html#functions.clipping ) // and there's four examples that use it in the demos in // the download archive. RGraph.clipTo.start(obj, 'tophalf'); }).on('draw', function (obj) { // This complements the above RGraph.clip.start() function and // ends clipping - returning the canvas to a neutral state. RGraph.clipTo.end(obj); }).trace(); // And this is the second, red Line chart that's shown on the // lower half of the chart. line2 = new RGraph.Line({ id: 'cvs', data: line1.data, // Set the options for the second chart. The ES6 "spread" operator (...) // is used here to reuse the options that were set in the first // object. Further options are then set in order to distinguish // it from the first chart. options: { ...line1.properties, colors: ['red'], filledColors: ['rgba(255,128,128,0.25)'], yaxisLabels: false, xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] } }).on('beforedraw', function (obj) { // Start clipping the canvas - this time to the lower half of // the canvas. RGraph.clipTo.start(obj, 'bottomhalf'); }).on('draw', function (obj) { // End clipping RGraph.clipTo.end(obj); }).trace();