Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I draw a table in canvas element?

Is there any way (plugins, working solutions, etc.) to draw a HTML table into a <canvas> element?

I have a rich-formatted html table (using CSS), and I want to save it as image (PNG, SVG or GIF) using jQuery. ...or if there any simpliest way, I'm listening it.

like image 726
netdjw Avatar asked Dec 21 '22 12:12

netdjw


1 Answers

Working DEMO

Sure, it is possible. You can draw DOM objects into a canvas. Here is the code you need:

<p><canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
             "<foreignObject width='100%' height='100%'>" +
               "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
                  "<table border='1'><tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr><tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr></table>" +
               "</div>" +
             "</foreignObject>" +
           "</svg>";

var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
};
img.src = url;
</script>​

You can find more information here on Mozilla Developer Network

like image 93
Gurpreet Singh Avatar answered Dec 31 '22 01:12

Gurpreet Singh