'Export SVG D3 js to PNG or JPEG and send by email
I have a javascript code that exports a svg d3 to a png or jpg image. When the svg is exported it sends an email (to send the email I use smtpjs) with the image, the image is downloaded perfectly but when I open it, it loses quality and almost all the graphics are erased, and the image that reaches the email comes empty. Is there a way to fix this?
**CODE: **
function svgString2Image(svgString, width, height, format, callback) {
var format = format ? format : 'png';
var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString)));// Convert SVG string to data URL
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
var image = new Image();
image.onload = function () {
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
canvas.toBlob(function (blob) {
var filesize = Math.round(blob.length / 1024) + ' KB';
if (callback) callback(blob, filesize);
});
};
image.src = imgsrc;
console.log(image.src)
Email.send({
SecureToken: "09f68b-d5e5-425-ba8-5d6b9419",
To: '[email protected]',
From: "[email protected]",
Subject: "This is the subject",
Body: "iuwaehfiuwreu",
Attachments: [
{
name: "smtpjs.png",
data: canvas.toDataURL()
//data: imgsrc
//data: image.src
}]
}).then(
message => alert(message)
);
}
Solution 1:[1]
I could repair it, modify some attributes of the context, which causes some parts of the graphic to be erased, what worked for me was to put the fillRect attribute blank and then draw the image. That worked for me.
context.fillStyle = "white";
context.fillRect(0, 0, w, h);
context.drawImage(image, 0, 0, w, h);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maifee Ul Asad |
