我的最终目标是将呈现的演示文稿MathML保存到.PNG文件中。知道编程是危险的:-)可能有更好的方法来做到这一点......我在canvas元素上绘制方程式,然后尝试将canvas元素保存为.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>−</mo>" +
"<mn>3</mn>" +
"</mtd>" +
"<mtd columnalign='center'> " +
"<mo>=</mo>" +
"</mtd>" +
"<mtd columnalign='left'> " +
"<mn>9</mn>" +
"<mo>−</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只是透明的(没有数学方程式)。我错过了什么?提前谢谢......
答案 0 :(得分: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;