2012-04-17 87 views
0

我的最終目標是將呈現的呈現MathML保存爲.PNG文件。只知道編程是危險的:-)可能有更好的方法來做到這一點...我在畫布元素上繪製方程,然後試圖將畫布元素保存爲.PNG。我開始與代碼在這裏找到 - https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas - 並作如下修改:將mathml呈現爲html5畫布爲png

<!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我可以看到MATHML在canvas元素,而是由toDataURL產生的.PNG是隻是透明的(沒有數學方程式)。我錯過了什麼?在此先感謝...

回答

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; 
+0

嗯,當我移動該語句時,出現「安全錯誤」。 – 2012-04-17 20:31:18

+0

看起來像它發生在toDataURL ...也許畫布是「髒」畢竟... – 2012-04-17 20:47:39

+0

只是「安全錯誤」 - 沒有代碼 – 2012-04-17 21:06:43