HOWTO: Use CSS3 transitions
By using CSS
transitions you can make smooth CSS
animations and effects for your canvas
tag. The effect shown below switches between two charts using a CSS
transition
and also changing the
CSS
width
and height
(the HTML
width
and height
attributes which set the width
and
height
of the canvas
remain unchanged). The code changes the CSS
width
and
height
settings at the correct times and the CSS
transition
does the rest.
The CSS
transition
is defined on the canvas
tag (in CSS
like this:
<style> canvas { transition: width .5s, height .5s, top .5s, left .5s; } </style>
<script> window.onload = (function () { // // Used to track which chart is currently being displayed // var type = true; // / This function is called to draw the bar chart // function drawBar () { var bar = new RGraph.Bar({ id: 'cvs', data: [5,8,16,5,8,9,4,3,2,4,3,2], options: { xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], textSize: 14 } }).draw(); type = false; } // // This function is called to draw the line chart // function drawLine () { var line = new RGraph.Line({ id: 'cvs', data: [5,8,16,5,8,9,4,3,2,4,3,2], options: { xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], textSize: 14 } }).draw(); type = true; } // // This is the onclick event for the button // document.getElementById('myButton').onclick = function (e) { var canvas = document.getElementById('cvs'); var $wrapper = $('#wrapper'); // // This CSS change results in the <canvas> shrinking (due to the CSS transition) // canvas.style.width = 0; canvas.style.height = 0; canvas.style.top = '100px' canvas.style.left = '300px'; // // Now that the <canvas> has been shrunk - wait 0.75 seconds, draw the alternate // chart and unshrink it. // setTimeout(function () { RGraph.reset(canvas); canvas.__rgraph_aa_translated__ = false; if (!type) { drawBar(); } else { drawLine(); } // // This CSS change results in the canvas expanding (due to the CSS transition) // canvas.style.width = '600px'; canvas.style.height = '250px'; canvas.style.position = 'relative'; canvas.style.left = 0; canvas.style.top = 0; }, 750) } drawBar(); }); </script>