Reputation: 8385
I'm drawing timeseries graphs with Chart.js which uses <canvas>
to draw. Our users would like to be able to download the images of these graphs to put in their reports. The site background is dark, so the graphs themselves are using light grey colours. This means that when the users right click (in Chrome) and select "save image as..." they get a transparent image with grey / white lines (obviously not terribly visible).
I have been trying to override canvas.toDataURL
in order to draw a rect first as in this post, but overriding doesn't work (I assume it's not writable). Is there another way of doing this?
Upvotes: 2
Views: 2993
Reputation: 5262
This should do the trick:
function getCanvasImage(_ctx, _bgColor){
var tmpCtx = document.createElement("canvas").getContext("2d");
tmpCtx.canvas.width = _ctx.canvas.width;
tmpCtx.canvas.height = _ctx.canvas.height;
tmpCtx.fillStyle = _bgColor;
tmpCtx.fillRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
tmpCtx.drawImage(_ctx.canvas, 0, 0);
return tmpCtx.canvas;
}
// ...
// just call the function passing your canvas context and the background color
var graphImage = getCanvasImage(ctx, "#222");
Upvotes: 1