Creating tables in HTML5 canvas

I have a project where I need to save an html table element as an image. It would seem that the best way to do this is to convert the data from the table to a canvas and then call toDataURL to get the image. After searching many of the tables mentioned here here , it looks like they all just put a wrapper around the normal html table to make it look more attractive.

  • Is there an easy way or library (this is not a fantasy) for drawing tabular data inside a canvas element?
  • Is there any other way I'm missing to save the contents of a table element to an image?

Since this is a Rails project, I would prefer the JS library to use JQuery.

EDIT

I forgot to mention that some of the entries in the table are links. Obviously this works well in a normal html table, but it also needs to work in the canvas version.

EDIT 2

Apparently I was wrong in the first edit. The version displayed to the user (be it a table or canvas) must contain links. The final image will obviously not be.

+3


source to share


1 answer


Here's an example (modified from: https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas )

http://jsfiddle.net/StEcW/1/

$(function() {
    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%'>" + $("#mytable").html() +
        "</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;
});

<div id="mytable">
    <div xmlns="http://www.w3.org/1999/xhtml" style='font-size:12px'>      
        <table border=1 id="amytable">
            <tr>
                <td>Hello</td>
                <td>There</td>
            </tr>        
        </table>
    </div>
</div>

      



This works pretty well, but see the fiddle for some weirdness around possible CSS that might not work perfectly right. At least in Chrome, the table border didn't display the same way for me.

Edit: of course it doesn't really make sense to go through the canvas. The canvas simply draws the image we have already created. All you have to do is show the image in the DOM.

+7


source







All Articles