0

我的最终目标是将呈现的演示文稿 MathML 保存到 .PNG 文件中。知道编程是危险的 :-) 可能有更好的方法来做到这一点......我在画布元素上绘制方程,然后尝试将画布元素保存为 .PNG。我从这里找到的代码开始——https: //developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas——并修改如下:

<!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>

如果我注释掉 window.open 我可以在 canvas 元素中看到 MathML,但 toDataURL 生成的 .PNG 只是透明的(没有数学方程式)。我错过了什么?提前致谢...

4

1 回答 1

0

我立即看到的问题是您将画布的渲染推迟到图像加载,但是您window.open在没有确保其已加载的情况下调用代码。您需要执行以下操作

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;
于 2012-04-17T19:17:11.493 回答