Has anyone tried using a svg to canvas library when creating d3.js visualizations? I've tried to use canvg.js and d3.js to convert svg to canvas from within an android 2.3 application webview, but when I call:
svg.selectAll(".axis")
.data(d3.range(angle.domain()[1]))
.enter().append("g")
.attr("class", "axis")
.attr("transform", function(d) { return "rotate(" + angle(d) * 180 / Math.PI + ")"; })
.call(d3.svg.axis()
.scale(radius.copy().range([-5, -outerRadius]))
.ticks(5)
.orient("left"))
.append("text")
.attr("y",
function (d) {
if (window.innerWidth < 455){
console.log("innerWidth less than 455: ",window.innerWidth);
return -(window.innerHeight * .33);
}
else {
console.log("innerWidth greater than 455: ",window.innerWidth);
return -(window.innerHeight * .33);
}
})
.attr("dy", ".71em")
.attr("text-anchor", "middle")
.text(function(d, i) { return capitalMeta[i]; })
.attr("style","font-size:12px;");
I get the error: Uncaught TypeError: Cannot call method setProperty of null http://mbostock.github.com/d3/d3.js?2.5.0:1707
Would some sort of headless browser application, or a server side js parser work? Has anyone encountered this before?
Here's one way you could write your svg to canvas (and then save the result as a png or whatever):
// Create an export button
d3.select("body")
.append("button")
.html("Export")
.on("click",svgToCanvas);
var w = 100, // or whatever your svg width is
h = 100;
// Create the export function - this will just export
// the first svg element it finds
function svgToCanvas(){
// Select the first svg element
var svg = d3.select("svg")[0][0],
img = new Image(),
serializer = new XMLSerializer(),
svgStr = serializer.serializeToString(svg);
img.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr);
// You could also use the actual string without base64 encoding it:
//img.src = "data:image/svg+xml;utf8," + svgStr;
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = w;
canvas.height = h;
canvas.getContext("2d").drawImage(img,0,0,w,h);
// Now save as png or whatever
};
The answer by #ace is very good, however it doesn't handle the case of external CSS stylesheets. My example below will automatically style the generated image exactly how the original SVG looks, even if it's pulling styles form separate stylesheets.
// when called, will open a new tab with the SVG
// which can then be right-clicked and 'save as...'
function saveSVG(){
// get styles from all required stylesheets
// http://www.coffeegnome.net/converting-svg-to-png-with-canvg/
var style = "\n";
var requiredSheets = ['phylogram_d3.css', 'open_sans.css']; // list of required CSS
for (var i=0; i<document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href) {
var sheetName = sheet.href.split('/').pop();
if (requiredSheets.indexOf(sheetName) != -1) {
var rules = sheet.rules;
if (rules) {
for (var j=0; j<rules.length; j++) {
style += (rules[j].cssText + '\n');
}
}
}
}
}
var svg = d3.select("svg"),
img = new Image(),
serializer = new XMLSerializer(),
// prepend style to svg
svg.insert('defs',":first-child")
d3.select("svg defs")
.append('style')
.attr('type','text/css')
.html(style);
// generate IMG in new tab
var svgStr = serializer.serializeToString(svg.node());
img.src = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(svgStr)));
window.open().document.write('<img src="' + img.src + '"/>');
};
And, to be complete, the button that calls the function:
// save button
d3.select('body')
.append("button")
.on("click",saveSVG)
.attr('class', 'btn btn-success')
Have you tried the same code on a browser supporting SVG to see if it's a problem with webview? Then try this example using canvg or this one using DOM serialization. For server-side rendering, you could start with this example for how to render it to canvas server-side using Node.js.
I've not tried a library, but have rendered a d3-produced SVG to a canvas following this post on MDN.
This code is a quick mish-mash of the MDN and some jQuery, that'll you'll need to tidy up, and it has no error- or platfrom-checking, but it works, and I hope it helps.
$(document.body).append(
'<canvas id="canvas" width="'+diameter+'" height="'+diameter+'"></canvas>'
);
// https://developer.mozilla.org/en/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
var el = $($('svg')[0]);
var svgMarkup = '<svg xmlns="http://www.w3.org/2000/svg"'
+ ' class="' + el.attr('class') +'"'
+ ' width="' + el.attr('width') +'"'
+ ' height="' + el.attr('height') +'"'
+ '>'
+ $('svg')[0].innerHTML.toString()+'</svg>';
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = this.URL || this.webkitURL || this;
var img = new Image();
var svg = new Blob([svgMarkup], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
alert('ok');
DOMURL.revokeObjectURL(url);
};
img.src = url;
Related
I have an interactive drawing app on my website, and I want to create a button where one could share their drawing on FB.
I'm trying to convert the SVG element to a blob, to then pass it to og:image, but I'm having some issues with the conversion.
I have two trials:
one doesn't trigger the onload function for some reason.
The other returns an empty blob
both trials work fine on jsfiddle however.
First Attempt
var xmlSerializer = new XMLSerializer();
var svgString = xmlSerializer.serializeToString(document.querySelector("#svg"));
var canvas = document.createElement("canvas");
var bounds = {
width: 1040,
height: 487
};
canvas.width = bounds.width;
canvas.height = bounds.height;
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {
type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
var mg = document.createElement("img");
mg.setAttribute("src", png);
document.body.appendChild(mg);
DOMURL.revokeObjectURL(png);
};
img.id = "testimg";
img.setAttribute("src", url);
Second Attempt
var svgString = new XMLSerializer().serializeToString(document.querySelector("svg"));
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || sel.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {
type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
var container = document.createElement('DIV');
container.innerHTML = '<img src="' + png + '"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;
document.body.appendChild(img);
Here's the app with the two attempts triggered by the two buttons "test1" and "test2"
The problem lies in the way you did define the xmlns:xlink attributes.
Currently from your page doing document.querySelector("use").attributes.getNamedItem("xmlns:xlink").namespaceURI will return null. This means that this attribute has been defined in the Document's namespace (HTML), so when you'll stringify it using the XMLSerializer, you will actually have two xmlns:xlink attributes on your elements, one in the HTML namespace, and the SVG one that is implied in an SVG embed in an HTML document.
It is invalid to have two same attributes on the same element in SVG, and thus your file is invalid and the image won't load.
If you are facing this issue it's certainly because you did set this attribute through JavaScript:
const newUse = document.createElementNS("http://www.w3.org/2000/svg", "use");
newUse.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
newUse.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#foo");
document.querySelector("svg").append(newUse);
console.log("set from markup:", document.querySelector("use").attributes.getNamedItem("xmlns:xlink").namespaceURI);
console.log("(badly) set from JS:", document.querySelector("use+use").attributes.getNamedItem("xmlns:xlink").namespaceURI);
// the last <use> has two xmlns:xlink attributes
console.log("serialization:", new XMLSerializer().serializeToString(document.querySelector("svg")));
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#foo"/>
</svg>
To set it correctly, you need to use setAttributeNS() and use the XMLNS namespace:
const newUse = document.createElementNS("http://www.w3.org/2000/svg", "use");
document.querySelector("svg").append(newUse);
// beware the last "/"
newUse.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
console.log("set from markup", document.querySelector("use").attributes.getNamedItem("xmlns:xlink").namespaceURI);
console.log("(correctly) set from JS", document.querySelector("use+use").attributes.getNamedItem("xmlns:xlink").namespaceURI);
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30">
<use xmlns:xlink="http://www.w3.org/1999/xlink"/>
</svg>
However the best is to not set at all these attributes.
As I said above, SVGs embedded in HTML do automatically have the correct xmlns and xlink namespaces defined without the need for attributes. And since you are creating your elements through JS, you already do define them in the correct namespace too.
So don't bother with these attributes:
const SVGNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(SVGNS, "svg");
// To be able to draw an SVG image on a canvas in Firefox
// you must set absolute width and height to the root svg node
svg.setAttribute("width", 50);
svg.setAttribute("height", 50);
const target = document.createElementNS(SVGNS, "symbol");
target.id = "target";
const rect = document.createElementNS(SVGNS, "rect");
rect.setAttribute("width", 50);
rect.setAttribute("height", 50);
rect.setAttribute("fill", "green");
const use = document.createElementNS(SVGNS, "use");
// since SVG2 we don't even need to set href in the xlink NS
use.setAttribute("href", "#target");
target.append(rect);
svg.append(target, use);
const svgString = new XMLSerializer().serializeToString(svg);
console.log(svgString); // contains all the NS attributes
const blob = new Blob([svgString], { type: "image/svg+xml" });
const img = new Image();
img.src = URL.createObjectURL(blob);
document.body.append(img);
I'm embedding an image on a d3 diagram as in this example:
var logoCanvas = d3.select("body").append("canvas")
.attr("id", "newCanvas")
.attr("width", width / 2)
.attr("height", height / 2)
.node();
var context = logoCanvas.getContext("2d");
var imageObj = new Image();
imageObj.src = 'myImage.svg';
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
var imageData = document.getElementById("newCanvas").toDataURL("image/png")
//Add as SVG image element
d3.select("svg").
append("image")
.datum(imageData)
.attr("height", 100)
.attr("width", 100)
.attr('transform', 'translate(' + [offsetX - 50, offsetY - 50] + ')')
.attr("xlink:href", function(d) {
return d
})
}
This works all as expected but unfortunately I get the image displayed twice. Basically I only need the appended one and not the one which is drawn onto the context. The thing is the I can't get the appended one without drawing it first.
Is there a way to hide the Image which is drawn in context?
Or a smarter approach of only getting one image displayed but embedded?
Here's a code snippet of an XMLHTTPRequest() and FileReader() approach to fetch a image and "embed" into a SVG. You don't need a canvas at all.
// append svg
d3.select("body").append("svg").attr("height", "300px").attr("width", "276px");
var xhr1 = new XMLHttpRequest();
xhr1.open('GET', 'https://s7.postimg.org/40f9flc1n/dummy1.png');
xhr1.responseType = 'blob';
xhr1.onload = function () {
var fs = new FileReader();
fs.onload = function (result) {
d3.select("svg").append("image")
.datum(result.target.result)
.attr("height", 300)
.attr("width", 276)
.attr("xlink:href", function(d) {
return d
})
};
fs.readAsDataURL(xhr1.response);
};
xhr1.send();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.7/d3.min.js"></script>
Hope this helps. :)
I would like to be able to write formulas in latex in a fabric.js canvas, perhaps with MathJax.
http://fabricjs.com/fabric-intro-part-2#text
Is it possible to do that?
I would use the SVG renderer of MathJax to create a SVG file and then load that SVG into fabric.js. Here's an example:
<!-- It is important to use the SVG configuration of MathJax! -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_SVG">
</script>
<!-- You might need at least Fabric 1.4.6, because of a bug with data URLs -->
<script type="text/javascript" src="https://raw.githubusercontent.com/kangax/fabric.js/master/dist/fabric.js">
</script>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script type="text/javascript">
// This function does the actual work
function tex(text, callback) {
// Create a script element with the LaTeX code
var div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "-1000px";
document.body.appendChild(div);
var se = document.createElement("script");
se.setAttribute("type", "math/tex");
se.innerHTML = text;
div.appendChild(se);
MathJax.Hub.Process(se, function() {
// When processing is done, remove from the DOM
// Wait some time before doing tht because MathJax calls this function before
// actually displaying the output
var display = function() {
// Get the frame where the current Math is displayed
var frame = document.getElementById(se.id + "-Frame");
if(!frame) {
setTimeout(display, 500);
return;
}
// Load the SVG
var svg = frame.getElementsByTagName("svg")[0];
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("version", "1.1");
var height = svg.parentNode.offsetHeight;
var width = svg.parentNode.offsetWidth;
svg.setAttribute("height", height);
svg.setAttribute("width", width);
svg.removeAttribute("style");
// Embed the global MathJAX elements to it
var mathJaxGlobal = document.getElementById("MathJax_SVG_glyphs");
svg.appendChild(mathJaxGlobal.cloneNode(true));
// Create a data URL
var svgSource = '<?xml version="1.0" encoding="UTF-8"?>' + "\n" + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' + "\n" + svg.outerHTML;
var retval = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgSource)));
// Remove the temporary elements
document.body.removeChild(div);
// Invoke the user callback
callback(retval, width, height);
};
setTimeout(display, 1000);
});
}
document.onload = function() {
var canvas = new fabric.Canvas("canvas");
tex("1+\\int_x^y e^x dx + \\ldots", function(svg, width, height) {
// Here you have a data url for a svg file
// Draw using FabricJS:
fabric.Image.fromURL(svg, function(img) {
img.height = height;
img.width = width;
canvas.add(img);
});
});
};
</script>
</body>
I've also put that into a JsFiddle: http://jsfiddle.net/3aHQc/39/
I tried to generate multiple canvases on the fly and when I create a new canvas, the previous one disappears. See here for an example:
http://jsfiddle.net/adrianh/5jspv/4/
Here is the javascript code:
var circleCount = 0;
function circleRect(rect)
{
var diameter = Math.sqrt(rect.width*rect.width+rect.height*rect.height);
var cx = (rect.right + rect.left)/2;
var cy = (rect.top + rect.bottom)/2;
var left = Math.floor(cx - diameter/2);
var top = Math.floor(cy - diameter/2);
diameter = Math.floor(diameter);
var html = "<canvas id='circleCanvas"+circleCount+"' "+
"width='"+(diameter+2)+"' "+
"height='"+(diameter+2)+"' "+
"style='"+
"position:absolute;"+
"z-index:0;"+
"left:"+(left-1)+"px;"+
"top:"+(top-1)+"px;"+
//"border:1px solid;"+
"' />";
alert(html);
var container = document.getElementById("circles");
container.innerHTML += html;
var c=document.getElementById("circleCanvas"+circleCount);
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(diameter/2+1,diameter/2+1,diameter/2,0,2*Math.PI);
ctx.stroke();
++circleCount;
}
$(".circled").each(function(i, obj) {
var rect = obj.getBoundingClientRect();
circleRect(rect);
});
Why is only one canvas showing up?
It will be more reliable to manipulate the DOM rather than trying to inline things with innerHTML. This code uses jQuery's DOM manipulation methods:
var circleCount = 0;
function circleRect(rect)
{
var diameter = Math.sqrt(rect.width*rect.width+rect.height*rect.height);
var cx = (rect.right + rect.left)/2;
var cy = (rect.top + rect.bottom)/2;
var left = Math.floor(cx - diameter/2);
var top = Math.floor(cy - diameter/2);
diameter = Math.floor(diameter);
var html = $("<canvas id='circleCanvas"+circleCount+"' "+
"width='"+(diameter+2)+"' "+
"height='"+(diameter+2)+"' "+
"style='"+
"position:absolute;"+
"z-index:0;"+
"left:"+(left-1)+"px;"+
"top:"+(top-1)+"px;"+
"' />");
$("#circles").append(html);
var ctx=html[0].getContext("2d");
ctx.beginPath();
ctx.arc(diameter/2+1,diameter/2+1,diameter/2,0,2*Math.PI);
ctx.stroke();
++circleCount;
}
You could also use the standard createElement and appendChild if you don't really need jQuery.
The innerHTML property has a number of drawbacks, although there is nothing specific I can find about not using += with it, the fact that insertAdjacentHTML exists would seem to indicate that you shouldn't really expect it to work well. (forgot this bit earlier) In this case, as you correctly surmised in your comment, the canvas you've drawn on is replaced by a new one when the assignment to innerHTML happens.
I'm using Google Chart for my application and I have to convert the generated chart to image byte code. I've done this in Firefox and Chrome but IE8 is not responding to get the svg element, So now I can't to get the byte code from the given div element. My script to convert div element to byte code is given below
function getElement() {
for (var i = 0; i < divelement.length; i++) {
toImg(document.getElementById(divelement[i]), i, medicalconditionid[i]);
}
}
function toImg(chartContainer, i, id) {
var field = document.createElement("input");
field.type = "hidden";
field.id = "img_code" + i;
field.name = "imgcode";
document.getElementById("dynamicText").appendChild(field);
document.getElementById('img_code' + i).value = id + "_" + getImgData(chartContainer);
i++;
}
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
I'm getting a Line: 85
Error: 'getElementsByTagName(...).0.parentNode' is null or not an object error in IE8.
I found in IE8 there is no support for svg or canvas element, so the javascript charting libraries like google charts, D3 and jqplot convert the charts to vml format so we cant to get the byte code as like above code. In my application google chart can produce image format charts that is deprecated but i used this image chart and send the image url to action class and convert the url to image. Refer this link for google image charts