For a project I am working on I need to transform a svg to png file. In order to do so I have found multiple guides and explanations online. One of these can be found here: Exporting D3 charts to PDF
In order to transform the svg to a png they use the following code:
let canvas = document.createElement('canvas');
canvg(canvas, svg);
let imgData = canvas.toDataURL('image/png');
But I keep on getting an error when I try to implement this in my own project: "TypeError: Cannot call a class as a function". I have found multiple explanations online where they use the canvg(canvas, svg); notation. I also have read the Github documentation form Canvg and found nothing about this type of notation or an alternative way to do this.
The way I import the package into my project is as follows:
import canvg from "canvg";
This is the full code I am using to convert my d3 svg chart to a pdf:
exportToPDF() {
let svg = document.getElementsByClassName("svg")[0].innerHTML;
var canvas = document.createElement("canvas");
canvg(canvas, svg);
let imgData = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", [1020, 768]);
doc.addImage(imgData, "PNG", 0, 0, 1020, 768);
doc.save("svg-png-chart.pdf");
}
The error is clear, you are calling the class canvg without the new keyword.
Also, you referred to the GitHub Documentation where there is clearly write how to use it:
window.onload = () => {
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// ==== HERE YOUR FUNCTION ===
v = canvg.Canvg.fromString(ctx, '<svg width="600" height="600"><text x="50" y="50">Hello World!</text></svg>');
// Start SVG rendering with animations and mouse handling.
v.start();
};
Probably the article you read Exporting D3 charts to PDF was refering to an older API of Canvg
This should do:
exportToPDF() {
let svg = document.getElementsByClassName("svg")[0].innerHTML;
let canvas = document.createElement("canvas");
let context = canvas.getContext('2d')
let v = canvg.Canvg.fromString(context, svg);
v.start();
let imgData = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", [1020, 768]);
doc.addImage(imgData, "PNG", 0, 0, 1020, 768);
doc.save("svg-png-chart.pdf");
}
I have a found the solution. The fix was also thanks to DDomen. He got me on the right path. canvg.fromString(context, svg) should be used in order to get the transform the svg to a png.
But then the next problem would arise that the dimensions need to be set on the canvas in order to have the imaged being cropped when it is bigger then the default dimensions of a canvas object.
exportToPDF() {
let svgElement = document.getElementsByClassName("svg")[0];
const width = svgElement.getBoundingClientRect().width;
const height = svgElement.getBoundingClientRect().height;
let svg = svgElement.innerHTML;
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
let v = canvg.fromString(context, svg);
v.start();
let imgData = canvas.toDataURL("image/png");
var doc = new jsPDF("l", "pt", [1020, 768]);
doc.addImage(imgData, "PNG", 0, 0, width, height);
doc.save("svg-png-chart.pdf");
}
Related
I'm trying to use the Incode functionality to resize an image in LogicApps.
I'm not sure if this is possible with the absence of HTML.
var inputImage = workflowContext.actions.GetFileContent.outputs.body.$content;
function resize_image(imagesrc)
{
let image = new Image();
var base = "data:image/png;base64,";
image.src = base.concat(imagesrc);
image.onload = () => {
let width = image.width;
let height = image.height;
let canvas = document.createElement('canvas');
canvas.width = newWidth ;
canvas.height = newHeight;
let context = canvas.getContext('2d');
context.drawImage(image, 450, 0, newWidth-500, newHeight);
}
return image;
}
return resize_image(inputImage);
The error I receive
The inline code action 'JavaScriptCode' execution failed, with error 'Image is not defined'.
$content is the image in Base64, for example, starts like this:
iVBORw0KGgoAAAANSUhEUgAACFwAAAMMCAYAAABkSiF3...
Inline code can only perform some simple JavaScript operations, it may not be able to install canvas.
You can create an Azure Function App to resize your image.
For more details, you can refer to Call functions from Azure Logic Apps.
I am trying to convert an external svg icon to a base64 png using a canvas. It is working in all browsers except Firefox, which throws an error "NS_ERROR_NOT_AVAILABLE".
var img = new Image();
img.src = "icon.svg";
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
};
Can anyone help me on this please? Thanks in advance.
Firefox does not support drawing SVG images to canvas unless the svg file has width/height attributes on the root <svg> element and those width/height attributes are not percentages. This is a longstanding bug.
You will need to edit the icon.svg file so it meets the above criteria.
As mentioned, this is an open bug caused by limitations on what Firefox accepts as specification for SVG sizes when drawing to a canvas. There is a workaround.
Firefox requires explicit width and height attributes in the SVG itself. We can add these by getting the SVG as XML and modifying it.
var img = new Image();
var src = "icon.svg";
// request the XML of your svg file
var request = new XMLHttpRequest();
request.open('GET', src, true)
request.onload = function() {
// once the request returns, parse the response and get the SVG
var parser = new DOMParser();
var result = parser.parseFromString(request.responseText, 'text/xml');
var inlineSVG = result.getElementsByTagName("svg")[0];
// add the attributes Firefox needs. These should be absolute values, not relative
inlineSVG.setAttribute('width', '48px');
inlineSVG.setAttribute('height', '48px');
// convert the SVG to a data uri
var svg64 = btoa(new XMLSerializer().serializeToString(inlineSVG));
var image64 = 'data:image/svg+xml;base64,' + svg64;
// set that as your image source
img.src = img64;
// do your canvas work
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
};
}
// send the request
request.send();
This is the most basic version of this solution, and includes no handling for errors when retrieving the XML. Better error handling is demonstrated in this inline-svg handler (circa line 110) from which I derived part of this method.
This isn't the most robust solution, but this hack worked for our purposes. Extract viewBox data and use these dimensions for the width/height attributes.
This only works if the first viewBox encountered has a size that accurately can represent the size of the SVG document, which will not be true for all cases.
// #svgDoc is some SVG document.
let svgSize = getSvgViewBox(svgDoc);
// No SVG size?
if (!svgSize.width || !svgSize.height) {
console.log('Image is missing width or height');
// Have size, resolve with new SVG image data.
} else {
// Rewrite SVG doc
let unit = 'px';
$('svg', svgDoc).attr('width', svgSize.width + unit);
$('svg', svgDoc).attr('height', svgSize.height + unit);
// Get data URL for new SVG.
let svgDataUrl = svgDocToDataURL(svgDoc);
}
function getSvgViewBox(svgDoc) {
if (svgDoc) {
// Get viewBox from SVG doc.
let viewBox = $(svgDoc).find('svg').prop('viewBox').baseVal;
// Have viewBox?
if (viewBox) {
return {
width: viewBox.width,
height: viewBox.height
}
}
}
// If here, no viewBox found so return null case.
return {
width: null,
height: null
}
}
function svgDocToDataURL(svgDoc, base64) {
// Set SVG prefix.
const svgPrefix = "data:image/svg+xml;";
// Serialize SVG doc.
var svgData = new XMLSerializer().serializeToString(svgDoc);
// Base64? Return Base64-encoding for data URL.
if (base64) {
var base64Data = btoa(svgData);
return svgPrefix + "base64," + base64Data;
// Nope, not Base64. Return URL-encoding for data URL.
} else {
var urlData = encodeURIComponent(svgData);
return svgPrefix + "charset=utf8," + urlData;
}
}
In general we can convert the HTML elements to string and then we can insert it into DOM later when needed. Similarly, I want to convert the "CANVAS" element to string along with its context properties.
In the following example, I am getting the string value of span tag with outerHTML property. Likewise I want to get the "CANVAS"element along with context properties.
Is there any method or property for this support?
Example code snippets:
var sp=document.createElement("span");
sp.innerHTML = "E2"
var e2 = sp.outerHTML;
$("#test1").append(e2);
var c=document.createElement("CANVAS");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
var cn = c.outerHTML;
$("#test2").append(cn);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
<span>E1</span>
</div>
<div id="test2">
</div>
Seems like you already know how to get dom properties of the canvas object.
Now you only need "context" infos (image data as I understand it)
You can get the image data as a base64 string like this:
function CreateDrawing(canvasId) {
let canvas = document.getElementById(canvasId);
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
}
function GetDrawingAsString(canvasId) {
let canvas = document.getElementById(canvasId);
let pngUrl = canvas.toDataURL(); // PNG is the default
// or as jpeg for eg
// var jpegUrl = canvas.toDataURL("image/jpeg");
return pngUrl;
}
function ReuseCanvasString(canvasId, url) {
let img = new Image();
img.onload = () => {
// Note: here img.naturalHeight & img.naturalWidth will be your original canvas size
let canvas = document.getElementById(canvasId);
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
}
img.src = url;
}
// Create something
CreateDrawing("mycanvas");
// save the image data somewhere
var url = GetDrawingAsString("mycanvas");
// re use it later
ReuseCanvasString("replicate", url);
<canvas id="mycanvas"></canvas>
<canvas id="replicate"></canvas>
In short no!
You should realize the difference between a standard DOM-element and a canvas-element:
A created DOM-element is part of the mark-up language that can be viewed and changed.
In the canvas a vector image is drawn based upon the rules created in script. These rules are not stored in the element as text but as the image and can't be subtracted from the canvas element.
However there are other possibilities. We can get the variables from the ctx-object. But no info about coordinates:
var c=document.createElement("CANVAS");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
var ctxInfo = [];
for (ctxKey in ctx)
{
if (Object.prototype.toString.call(ctx[ctxKey]) !== "[object Function]" )
{
ctxInfo.push(ctxKey + " : " + ctx[ctxKey]);
}
}
console.log(ctxInfo);
To transfer from one canvas to the other I would keep a list (array or object) of instructions and write a generic function that applies them.
canvasObject = [["beginPath"], ["moveTo", 20, 20], ["lineTo", 100, 20], ["arcTo", 150, 20, 150, 70, 50], ["lineTo", 150, 120], ["stroke"]];
function createCanvas(cnvsObj)
{
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
cnvsObj.forEach(function(element){
//loop through instructions
ctx[element[0]].apply(ctx, element.slice(1));
});
return c;
}
var a = createCanvas(canvasObject);
document.body.appendChild(a);
I've seen this question on Stackoverflow, but I failed to find an answer - all solutions proposed just does not work for me.
Problem: When I'm passing a base64-encoded SVG as src to image it looks as crisp as original SVG image. But if I'll take this image and use it in canvas (via context.drawImage) - it would be of a worser quality:
The question is - how can I draw svg-based image in canvas which will look like original image?
What have I tried so far. The approach described here (re-iterative downsampling) is not working for me. The other advise (to add 0.5 to the dimensions) has not saved the situation as well. Playing with imageSmoothingEnabled - still no luck.
Here's the codepen used for generating this particular screenshot:
let toBase64 = (svg) => {
let serialized = new XMLSerializer().serializeToString(svg);
let base64prefix = "data:image/svg+xml;base64,"
let enc = base64prefix + btoa(serialized);
return enc;
}
let copySvg = (svg, img) => {
let enc = toBase64(svg);
img.src = enc;
}
let copyImg = (img, canvas) => {
context = canvas.getContext("2d");
context.drawImage(img, 0, 0, 200.5, 200.5);
}
let main = () => {
let svg = document.getElementById("svg");
let img = document.getElementById("img");
let canvas = document.getElementById("canvas");
copySvg(svg, img);
copyImg(img, canvas);
}
window.onload = main;
The SVG and Image are implicitly drawn at high DPI, but you need to explicitly handle this case for canvas.
If your device has window.devicePixelRatio === 2, you'll see a much crisper image if you increase canvas size and update drawImage to match:
<!-- Change this -->
<canvas id="canvas" width="200" height="200"></canvas>
<!-- to -->
<canvas id="canvas" width="400" height="400"></canvas>
And:
// change this:
context.drawImage(img, 0, 0, 200.5, 200.5);
// to:
context.drawImage(img, 0, 0, 400, 400);
Forked codepen
For more details about window.devicePixelRatio (and canvas's backingStorePixelRatio) see the html5rocks article on High DPI Canvas
I want to converty my SVG into CANVAS and then save it as image. I have svg already genereated by javascript in my page. I use this code:
$("#menu-save-image").click(function () {
var svg = document.getElementsByTagName('svg');
var canvas = document.getElementById("test");
canvg(canvas, svg);
// or second way
var c = document.getElementById('test');
var ctx = c.getContext('2d');
ctx.drawSvg(svg, 0, 0, 500, 500);
});
Both ways doesn't work. Why?
canvg method needs SVG source string (or url or XMLDocument), so you should convert the svg element to svg source by using XMLSerializer like this.
var svg = document.querySelector('svg');
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svg);
var canvas = document.getElementById("test");
canvg(canvas, svgString);
see https://code.google.com/p/canvg/source/browse/trunk/canvg.js