Use canvas.drawImage instead of canvg for better results.

This commit is contained in:
Przemek Wiech
2019-03-03 00:04:34 +01:00
parent 1dc90e3262
commit 1083708e15
2 changed files with 13 additions and 19 deletions

View File

@@ -4,7 +4,6 @@
"main": "src/index.tsx", "main": "src/index.tsx",
"dependencies": { "dependencies": {
"canvas-toBlob": "^1.0.0", "canvas-toBlob": "^1.0.0",
"canvg": "^1.5.3",
"d3": "^5.7.0", "d3": "^5.7.0",
"detect-browser": "^4.1.0", "detect-browser": "^4.1.0",
"file-saver": "^2.0.1", "file-saver": "^2.0.1",

View File

@@ -139,7 +139,7 @@ export class Chart extends React.PureComponent<ChartProps, {}> {
private getSvgContents() { private getSvgContents() {
const svg = document.getElementById('chart')!.cloneNode(true) as Element; const svg = document.getElementById('chart')!.cloneNode(true) as Element;
svg.removeAttribute('transform'); svg.removeAttribute('transform');
return svg.outerHTML; return new XMLSerializer().serializeToString(svg);
} }
/** Shows the print dialog to print the currently displayed chart. */ /** Shows the print dialog to print the currently displayed chart. */
@@ -175,24 +175,19 @@ export class Chart extends React.PureComponent<ChartProps, {}> {
canvas.width = svg.getBBox().width * 2; canvas.width = svg.getBBox().width * 2;
canvas.height = svg.getBBox().height * 2; canvas.height = svg.getBBox().height * 2;
// Fill canvas with white background. const blob = new Blob([this.getSvgContents()], {type: 'image/svg+xml'});
const ctx = canvas.getContext('2d')!;
const oldFill = ctx.fillStyle;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = oldFill;
canvg(canvas, this.getSvgContents(), { const img = new Image();
ignoreDimensions: true, img.onload = () => {
ignoreClear: true, const ctx = canvas.getContext('2d')!;
scaleWidth: canvas.width, ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
scaleHeight: canvas.height, const onBlob = (blob: Blob | null) => {
}); if (blob) {
const onBlob = (blob: Blob | null) => { saveAs(blob, 'topola.png');
if (blob) { }
saveAs(blob, 'topola.png'); };
} canvas.toBlob(onBlob, 'image/png');
}; };
canvas.toBlob(onBlob, 'image/png'); img.src = URL.createObjectURL(blob);
} }
} }