How can I convert d3 SVG element to canvas?
I got this working on web-chrome browser but it is not working in iOS safari:
Used this example. This example also not work on iOs safari but works on chrome desktop Ref: http://bl.ocks.org/syntagmatic/1dd1acd35f77c1fc64863e42f4a405bb
Function for SVG to Canvas:
function svgToCanvas() {
// d3.select("#aloft-canvas-container").html("");
var devicePixelRatio = window.devicePixelRatio || 1;
var canvas = d3.select("#aloft-canvas-container").append("canvas")
.attr("width", (width) * devicePixelRatio)
.attr("height", (ceilingChartHeight + topMarginFactor + xAxisTopContainerHeight) * devicePixelRatio)
.style("width", width + "px")
.style("height", (ceilingChartHeight+ topMarginFactor + xAxisTopContainerHeight) + "px")
.style("position", "absolute");
var context = canvas.node().getContext("2d");
context.scale(devicePixelRatio, devicePixelRatio);
// Convert SVG to Canvas
// see: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
var DOMURL = window.URL || window.webkitURL || window;
var svgNode = d3.select("#meteo-barbs-container").node(),
serializer = new XMLSerializer();
// var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + serializer.serializeToString(svgNode) + '</svg>';
var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + domNodeToString(svgNode) + '</svg>';;
console.log(svgString);
var image = new Image();
var svgBlob = new Blob([svgString], {
type: "image/svg+xml"
});
var url = DOMURL.createObjectURL(svgBlob);
image.onload = function () {
context.drawImage(image, 0, 0);
DOMURL.revokeObjectURL(url);
d3.select("#meteo-barbs-container").remove();
}
image.src = url;
};
In iOS it is drawing only half canvas. Not sure what is happening :-(
Use of canvg library simplifies all this :-)
https://github.com/canvg/canvg
contents.convertSvgToCanvas = function (sourceSvgId, canvasContainerId, canvasId, canvasWidth, canvasHeight, callback) {
var serializer = new XMLSerializer();
var svgNode = d3.select("#" + sourceSvgId).node();
var devicePixelRatio = window.devicePixelRatio || 1;
d3.select("#" + canvasContainerId).append("canvas")
.attr("id", canvasId)
.attr("width", (canvasWidth) * devicePixelRatio)
.attr("height", (canvasHeight) * devicePixelRatio)
.style("position", "absolute");
if (svgNode) {
var cv = document.getElementById(canvasId);
var ctx = cv.getContext("2d");
var pixelRatio = window.devicePixelRatio || 1;
cv.style.width = cv.width + "px";
cv.style.height = cv.height + "px";
cv.width *= pixelRatio;
cv.height *= pixelRatio;
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
canvg(document.getElementById(canvasId), serializer.serializeToString(svgNode));
callback();
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.