PhantomJS renders blurry Chart.js canvas
For Phantom 2, I rendered the charts with a large canvas to get the resolution up and then converted it into a png finally destroying and removing the old canvas and replacing them with an image with responsive CSS classes. Adjusting the knobes on the canvas width and height in addition to Chart.js options will get you a perfect render. We were able to get our rendering speed up with the approach (alternative to SVG renders) and the file size down.
HTML:
<div class="container">
<!-- generated images -->
<img id="someIdImage" class="img-responsive"></img>
<!-- temporary canvas -->
<canvas id="someId" width="2000" height="600"></canvas>
</div>
Javascript:
/**
* _plot() plot with Chart.js
*
* @param {Function} callback
*/
function _plot(callback) {
var config = {}; // some Chart.js config
var id = 'someId';
var el = document.querySelector('#' + id);
var el2d = el.getContext('2d');
// plot instance
var instance = new Chart(el2d, config);
// generate and append image
document.querySelector('#' + id + 'Image').setAttribute('src', el.toDataURL('image/png'));
// destroy instance
instance.destroy();
el.parentElement.removeChild(el);
// callback
if (callback) {
callback();
}
}
Add viewportSize and zoomFactor in your phantomjs page:
await page.property('viewportSize', { height: 1600, width: 3600 });
await page.property('zoomFactor', 4);
and add in your html head template
<script>
window.devicePixelRatio = 4;
</script>
Try setting the zoom factor using a higher DPI for paper in relation to screen DPI:
page.zoomFactor = 300 / 96; // or use / 72
Must be set after page size is defined.
You could also check out this answer:
Poor quality of png images drawn into html canvas