5

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.

netdjw
  • 5,419
  • 21
  • 88
  • 162
  • I don't think you can access the pixel data of rendered HTML elements with JS (without using any browser plugin) – Damp Dec 16 '12 at 18:07
  • You should check [this answer](http://stackoverflow.com/a/6789627/1102014) and after it created a screenshot on canvas, you can get picture by calling `canvas.toDataURL();`. – Stan Dec 16 '12 at 18:25
  • Yep, I'm trying to parse how it works :) Possibly you have some working example? – netdjw Dec 16 '12 at 18:35

1 Answers1

12

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

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
  • This is great! Thank you! I'm new for SVG. Can you help me how can I use my `CSS` file for this generated `SVG` image? – netdjw Dec 16 '12 at 21:15
  • Not sure if you can use external css styles. Check out the link for more information that I supplied in this answer. – Gurpreet Singh Dec 16 '12 at 21:40
  • 1
    I know this is an old answer, but there should be a note about the fact that this will taint the canvas in all browsers except Edge and Firefox, thus making all programmatic exports unavailable. – Kaiido Dec 19 '16 at 07:08
  • Your provided link is no longer available! – autopilot Jan 16 '20 at 10:27
  • 1
    @autopilot - an alternate [link](https://reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas) – ashleedawg Nov 10 '20 at 04:01