0

My ultimate goal is to save rendered presentation MathML to a .PNG file. Knowing just enough about programming to be dangerous :-) there may be a better way to do this...I am drawing the equation on a canvas element, then trying to save the canvas element as a .PNG. I started with code found here -- https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas -- and modified as follows:

<!DOCTYPE html>
<html>
<body>
<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/1998/Math/MathML'     style='fontsize:40px'>" +
        "<math>" +
        "<mtable>" +
        "<mtr>" +
        "<mtd columnalign='right'>" +
            "<mn>2</mn>" +
            "<mi>x</mi>" +
            "<mo>+</mo>" +
            "<mn>3</mn>" +
            "<mo>&#8722;</mo>" +
            "<mn>3</mn>" +
         "</mtd>" +
         "<mtd columnalign='center'> " +              
            "<mo>=</mo>" +
        "</mtd>" +
        "<mtd columnalign='left'> " +              
            "<mn>9</mn>" +
            "<mo>&#8722;</mo>" +
            "<mn>3</mn>" +
         "</mtd>" +
        "</mtr>" +
        "</mtable>" +
        "</math>" +
        "</div>" +
        "</foreignObject>" +
        "</svg>";

var svg = new (self.BlobBuilder || self.MozBlobBuilder || self.WebKitBlobBuilder);
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
svg.append(data);
var url = DOMURL.createObjectURL(svg.getBlob("image/svg+xml;charset=utf-8"));
img.onload = function() {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
};
img.src = url;

window.open(canvas.toDataURL('image/png'));

</script>

</body>
</html>

If I comment out the window.open I can see the MathML in the canvas element, but the .PNG generated by the toDataURL is just transparent (no math equations). What am I missing? Thanks in advance...

1 Answers1

0

Right off the bat the issue I see is that you defer the rendering of the canvas until the image loads, but you call window.open in the code without making sure its loaded. You would need to do something like the following

img.onload = function() {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
    // now the image has been drawn for sure *before* opening the window
    window.open(canvas.toDataURL('image/png'));
};
img.src = url;
Loktar
  • 34,764
  • 7
  • 90
  • 104