简体   繁体   English

canvas.toDataURL('image/svg+xml') 返回 "data:image/png;base64..."

[英]canvas.toDataURL('image/svg+xml') returning "data:image/png;base64..."

I am trying to export the canvas into svg .我正在尝试将画布导出到 svg 。 but the toDataURL function returning the data as "data:image\/png;base64..."但 toDataURL 函数将数据返回为“data:image\/png;base64...”

I don't want to use complex function\/library .<\/em>我不想使用复杂的函数\/库。<\/em>

I am using the below if any one can modify it also ,it is helpful for me如果有人也可以修改它,我正在使用以下内容,这对我有帮助

             var dataURL=canvas.toDataURL('image/svg+xml');
             if (navigator.userAgent.indexOf("Safari") > -1 && 
             navigator.userAgent.indexOf("Chrome") === -1) {
                console.log(dataURL);
                window.open(dataURL);
              } else {
                 var parts = dataURL.split(';base64,');
                  var contentType = parts[0].split(":")[1];
                  var raw = window.atob(parts[1]);
                  var rawLength = raw.length;
                  var uInt8Array = new Uint8Array(rawLength);
                    console.log(uInt8Array);

                  for (var i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                  }

                var blob = new Blob([uInt8Array], {type: "image/svg+xml;charset=utf-8"});
                var url = window.URL.createObjectURL(blob);

                var a = document.createElement("a");
                a.style = "display: none";
                a.href = url;
                a.download = orientation +".svg";

                document.body.appendChild(a);
                a.click();

                window.URL.revokeObjectURL(url);

The <canvas> element only holds a pixels buffer. <canvas> 元素只包含一个像素缓冲区。
Even though the 2D API is mostly based on vector drawings, the actual content is only raster.尽管 2D API 主要基于矢量图,但实际内容只是光栅。

Exporting to svg is not an option in any mainstream browser.导出到 svg 不是任何主流浏览器的选项。

This means that your 'image/svg+xml' will not be recognized anywhere and indeed they will fallback to image/png .这意味着您的'image/svg+xml'不会在任何地方被识别,实际上它们会回退到image/png

You said you don't want to use complex function/library, so let's just say you're out of luck, because the solutions implies to overwrite all the drawing operations in order to build pathes that can be mapped to SVG elements, which is not straightforward, (even if all is mostly doable, except ImageData pixel manips).你说你不想使用复杂的函数/库,所以让我们说你运气不好,因为解决方案意味着覆盖所有的绘图操作以构建可以映射到 SVG 元素的路径,这是并不简单,(即使大部分都是可行的,除了 ImageData 像素操作)。
If you really want to do this, then you may want to have a look at some libraries, this one seems to be made only for this purpose, so I hope it's lightweight an performant enough, though I never used it myself, fabricjs has such an option too, but then we're clearly in the heavy-weighted category.如果你真的想这样做,那么你可能想看看一些库,这个似乎只是为了这个目的,所以我希望它足够轻量级和高性能,虽然我自己从未使用过它, fabricjs有这样的也是一个选项,但我们显然属于重量级类别。

my vanilla js solution may help you, without using the canvas.toDataURL<\/code> way我的 vanilla js 解决方案可能会对您有所帮助,而无需使用canvas.toDataURL<\/code>方式<\/h2>

steps脚步<\/h2>
  1. get or create an SVG element获取或创建 SVG 元素

    <\/li>

  2. use the XMLSerializer().serializeToStrin()<\/code> serialize method get SVG string使用XMLSerializer().serializeToStrin()<\/code>序列化方法获取 SVG 字符串

    <\/li>

  3. use window.btoa()<\/code> method to convert SVG string to base64 String使用window.btoa()<\/code>方法将 SVG 字符串转换为 base64 字符串

    <\/li>

  4. manually create the data:image\/svg+xml;<\/code>手动创建data:image\/svg+xml;<\/code> type base64 URL string输入 base64 URL 字符串

    <\/li>

  5. then do something you wanted;然后做你想做的事; for example, download the image an so on.例如,下载图像等等。

    <\/li><\/ol>

    source codes源代码<\/h2>

     const userName = "xgqfrms"; const watermark = ` <svg xmlns="http:\/\/www.w3.org\/2000\/svg" version="1.1" id="svg" viewBox="0 0 100 100" width="100" height="100"> <text x="25" y="50" fill="#00ff00">${userName}<\/text> <\/svg> `; const app = document.querySelector(`#app`); app.insertAdjacentHTML('beforeend', watermark); const svgElement = document.querySelector(`#svg`); \/\/ console.log(`svgElement =`, svgElement); const svgURL = new XMLSerializer().serializeToString(svgElement); \/\/ console.log(`svgURL =`, svgURL); const imgSrc = `data:image\/svg+xml;base64,${window.btoa(svgURL)}`; console.log(`imgSrc =`, imgSrc); const img = document.querySelector(`#img`); img.src = imgSrc;<\/code><\/pre>
     #app > svg { visibility: hidden; width: 0; height: 0; } #app { width: 100vw; height: 100vh; min-width: 1366px; min-height: 768px; overflow-x: hidden; overflow-y: auto; }<\/code><\/pre>
     <!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="author" content="xgqfrms"> <meta name="generator" content="VS code"> <title>js canvas to base64 svg image<\/title> <\/head> <body> <main id="app"> <img id="img" src=""\/> <\/main> <\/body> <\/html><\/code><\/pre>

    demo演示<\/h2>

    https:\/\/codepen.io\/xgqfrms\/pen\/YzEzmxw<\/a> https:\/\/codepen.io\/xgqfrms\/pen\/YzEzmxw<\/a>

    "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Canvas.toDataUrl(“ image / png”)无法正常工作 - Canvas.toDataUrl(“image/png”) is not working properly JavaScript中“ canvas.toDataURL(” image / png“);”的替代形式? - Alternatives to “canvas.toDataURL(”image/png“);” in JavaScript? Javascript canvas.toDataURL()返回空白图像 - Javascript canvas.toDataURL() returning Blank image 如何转换data:image / svg + xml;来自自然图像的base64数据? - How to convert data:image/svg+xml;base64 data from natural image? image.src = canvas.toDataURL(“image/png”); 保存问题 - image.src = canvas.toDataURL(“image/png”); Saving issue “canvas.toDataURL(”image / png“)”在firefox中无法正常工作 - “canvas.toDataURL(”image/png“)” not working properly in firefox canvas.toDataURL(“ image / png”)-如何工作以及如何对其进行优化 - canvas.toDataURL(“image/png”) - how does it work and how to optimize it 为什么canvas.toDataURL()不能为图像生成与Ruby中相同的base64? - Why does canvas.toDataURL() not produce the same base64 as in Ruby for an image? 如何使用canvas.toDataURL()在Adobe AIR中获取图像的base64? - How to use canvas.toDataURL() to get base64 of image in Adobe AIR? Firefox:image.onload中的canvas.toDataURL,但返回透明图像 - Firefox : canvas.toDataURL in image.onload but returning transparent image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM