2011-08-17 111 views
2

我在检索画布上显示的图像的base64版本时遇到问题。我已经看了其他问题,但没有任何解决方案,包括canvas2image似乎工作。HTML画布图像到Base64问题

这里是我的代码:

<!DOCTYPE> 
<html> 
<head> 
    <style>#canvas {cursor: pointer;}</style> 
</head> 
<body> 
    <canvas id="canvas"></canvas> 

    <script type="text/javascript"> 

     var can = document.getElementById('canvas'); 
     var ctx = can.getContext('2d'); 

     var img = new Image(); 
     img.onload = function(){ 
      can.width = img.width; 
      can.height = img.height; 
      ctx.drawImage(img, 0, 0, img.width, img.height); 
     } 
     img.src = 'http://sstatic.net/stackoverflow/img/newsletter-ad.png'; 

     can.onclick = function() { 
      ctx.translate(img.width-1, img.height-1); 
      ctx.rotate(Math.PI); 
      ctx.drawImage(img, 0, 0, img.width, img.height); 
     }; 

    document.write(can.toDataURL()); //isn't writing the correct base64 image 


    </script> 
</body> 
</html> 

这里的测试环节:http://jsfiddle.net/mrchief/hgTdM/1/感谢,Mrchief

我需要的是在画布上的图像的base64输出正确的。

问题是,它不会输出正确的base64版本的图像..但正如你所看到的,画布内的图像显示没有任何问题。

我已经测试了镀铬&火狐

非常感谢..

+0

那么,输出什么* *然后呢? –

+2

在Chrome&FF5中适合我:http://jsfiddle.net/mrchief/hgTdM/1/ – Mrchief

+0

在IE9和Firefox 6中可以正常工作。 – Caimen

回答

2

document.write()呼叫立即出现在网页加载时,您img之前被加载并绘制和你onclick处理程序可以运行前。您需要等待生成数据URI,直到所有内容都发生在画布上。

忽略onclick,这里的东西,写出来的数据链接的图像加载和被吸引到画布在旋转方式后:

<!DOCTYPE html> 
<html><head> 
    <title>Rotated Image Data URL</title> 
    <style type="text/css" media="screen"> 
    canvas, textarea { display:block } 
    </style> 
</head><body> 
    <canvas id="canvas"></canvas> 
    <textarea id="data" rows="20" cols="80"></textarea> 
    <img id="echo"> 
    <script type="text/javascript"> 
     var can = document.getElementById('canvas'); 
     var ctx = can.getContext('2d'); 

     var img = new Image(); 
     img.onload = function(){ 
     can.width = img.width; 
     can.height = img.height; 
     ctx.translate(img.width-1, img.height-1); 
     ctx.rotate(Math.PI); 
     ctx.drawImage(img, 0, 0, img.width, img.height); 
     var url = document.getElementById('data').value = can.toDataURL(); 
     document.getElementById('echo').src = url; 
     } 
     img.src = 'gkhead.jpg'; 
    </script> 
</body></html> 

你可以在这里看到这些内容起作用演示:http://phrogz.net/tmp/upside-down-image-url.html

请注意,您加载的图像必须与您的脚本位于同一个域中,否则您将无法创建数据网址。

+0

感谢phrogz。问题在于图像位于不同的域上。我不得不用PHP来解决这个问题。 – blmic