canvas.toDataUrl返回"data :;".当canvas.width/height太大时 [英] canvas.toDataUrl returns "data:;" when canvas.width/height is too large

查看:1110
本文介绍了canvas.toDataUrl返回"data :;".当canvas.width/height太大时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行svg导出png图像功能. 首先我将svg生成为base64,其base64标头类型也为svg+xml,然后

I need to do a svg export png image function. First I generate svg to base64, with the base64 header type too svg+xml, then

var image=new Image();
image.src=base64Code;
image.onload = function() {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      canvas.width = image.width;
      canvas.height = image.width;
      context.drawImage(image, 0, 0);
      png = canvas.toDataURL("image/png",1);
}`

我的canvas.width/height可能很大.
当我使用canvas.toDataURL时,它将返回"data:;". canvas.width/height更合理时,结果正确.

My canvas.width/height may be very large.
When I use canvas.toDataURL it returns "data:;". When the canvas.width/height is more reasonable, the result is correct.

有什么好办法解决这个问题吗?还是使用javascript将svg+xml转换为.png?

Is there any good way to deal this? Or use javascript to convert from svg+xml to .png?

推荐答案

Canvas元素的最大大小在浏览器实现中会有所不同. 您可以在此Q/A 中找到这些最大尺寸的良好列表.

Canvas element has maximum size which will be different across browser implementations. You can find a good list of these maximum dimensions in this Q/A.

它们对导出方法也有限制. 在我的Chrome浏览器中,toDataURL返回与 16380 * 16380 宽的画布相同的data:;,而我的Firefox确实在 11150 * 11150 <处抛出了NS_ERROR_FAILURE/strong>. 其他浏览器可能会根据自己的实现而具有不同的值.

They also have limits for the export methods. In my Chrome, toDataURL returns the same data:; as you've got for canvas around 16380 * 16380 wide and my Firefox does throw an NS_ERROR_FAILURE at around 11150 * 11150. Other browsers might have different values depending on their own implementation.

因此,如果您真的想通过画布,则必须将画布的大小限制为这些最大区域.

So, if you really want to pass through canvas, you will have to limit the size of your canvas to these maximum areas.

现在,如果可以在服务器端进行转换,则可以使用它. Batik 被认为是很好的SVG UA,并且应该能够正确转换SVG,除非在SVG的<foreignObject>元素内还可以渲染HTML.

Now, if you can do the conversion server-side, you can go with it. Batik is known to be a good SVG UA and should be able to convert your SVGs correctly, except when there is also HTML to render inside an SVG's <foreignObject> element.

在这种情况下,最好的方法是像 phantomjs 这样的无头浏览器,它可以拍摄渲染页面的真实屏幕截图.

In this case, an headless browser like phantomjs, allowing to take real screenshots of a rendered page seems to be the best way.

另一种方法是将较大的SVG绘制到较小的画布上,然后在服务器端或通过字节操作合并生成的PNG图像(可能需要一些额外的工作).

An other way would be to draw your large SVG onto smaller canvas and merge the resulting PNG images either server-side or through byte manipulation (might need some extra work).

这篇关于canvas.toDataUrl返回"data :;".当canvas.width/height太大时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆