问题
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);
}`
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.
Is there any good way to deal this? Or use javascript to convert from svg+xml
to .png?
回答1:
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.
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.
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.
In this case, an headless browser like phantomjs, allowing to take real screenshots of a rendered page seems to be the best way.
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).
回答2:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeRect(5, 5, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);
</script>
</body>
</html>
HTML canvas scale() Method
you can use this method, maybe it can work
return 'data:;' maybe the url is too large
来源:https://stackoverflow.com/questions/43860035/canvas-todataurl-returns-data-when-canvas-width-height-is-too-large