2011-06-22 90 views

回答

4

爲了將畫布保存爲圖像文件,您可以使用Nihilogic's code

使用canvas text functions

例如:

<html> 
    <head> 
    <title>Canvas tutorial</title> 
    <script type="text/javascript"> 
     function draw(){ 
     var canvas = document.getElementById('tutorial'); 
     if (canvas.getContext){ 
      var ctx = canvas.getContext('2d'); 
      ctx.fillText("Sample String", 10, 50); 
     } 
     } 
    </script> 
    <style type="text/css"> 
     canvas { border: 1px solid black; } 
    </style> 
    </head> 
    <body onload="draw();"> 
    <canvas id="tutorial" width="150" height="150"></canvas> 
    </body> 
</html> 
+1

如果我沒看錯,鏈接指定如何繪製在畫布上的文字。我想創建一個圖像。 – user475685

+1

哦,對不起。你是什​​麼意思「創造一個形象」?允許用戶將圖像保存在他的硬盤上?看看我更新的答案,那是你的意思? –

+0

不保存,但在瀏覽器中顯示爲圖像。 – user475685

0

創建圖像DOM元素,和Src設置爲canvas.toDataURL方法。

var c = document.getElementById("c"); 
 
var ctx = c.getContext("2d"); 
 
ctx.fillStyle = "red"; 
 
ctx.fillRect(10, 10, 50, 50); 
 

 
function copy() { 
 
    
 
     var image = document.getElementById("Img"); 
 
      image.src = c.toDataURL("image/png"); 
 

 

 
}
<canvas id="c" width="300" height="150" style="border:1px solid #d3d3d3;"> 
 
Your browser does not support the HTML5 canvas tag.</canvas> 
 
<img id="Img" width="300" height="150" style="border:1px solid #d3d3d3;"/> 
 
<button onclick="copy()">Copy</button>