Rendering Raphael to Canvas for Printing

by gbos

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.4/canvg.min.js"></script>
<div id="holder"></div>
<canvas id="mycanvas">Upgrade or change browser!</canvas>



<script type="text/javascript" src="http://gabelerner.github.io/canvg/rgbcolor.js"></script> 
<script type="text/javascript" src="http://gabelerner.github.io/canvg/StackBlur.js"></script>

CSS

#holder, #mycanvas {
    width: 300px;
    height: 300px;
}

/* comment out the entire set of selectors below to see the canvas element as well
@media screen {
  #mycanvas {
      display: none;
    }
}

@media print {
  #holder {
      display: none;
    }
}*/

JavaScript

Raphael.fn.ball = function (x, y, r, hue) {
    hue = hue || 0;
    return this.set(this.ellipse(x, y + r - r / 5, r, r / 2)
        .attr({
        fill: "rhsb(" + hue + ", 1, .25)-hsb(" + hue + ", 1, .25)",
        stroke: "none",
        opacity: 0
    }), this.ellipse(x, y, r, r).attr({
        fill: "r(.5,.9)hsb(" + hue + ", 1, .75)-hsb(" + hue + ", .5, .25)",
        stroke: "none"
    }), this.ellipse(x, y, r - r / 5, r - r / 20).attr({
        stroke: "none",
        fill: "r(.5,.1)#ccc-#ccc",
        opacity: 0
    }));
};

(function () {
    var R = Raphael("holder");
    
    R.ball(R.width * 0.5, R.height * 0.5, 
           Math.min(R.width, R.height) * 0.35, Math.random());
    
    // after rendering the Raphael element, we pass the SVG string
    // to canvg library where the canvas element is made visible on
    // CSS using print media selector
    console.log(document.getElementById('holder').innerHTML)
    canvg("mycanvas", document.getElementById('holder').innerHTML);
}());