我想通过JavaScript将SVG转换为位图图像(如JPEG, PNG等)。


当前回答

这似乎在大多数浏览器中都有效:

function copyStylesInline(destinationNode, sourceNode) {
   var containerElements = ["svg","g"];
   for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
       var child = destinationNode.childNodes[cd];
       if (containerElements.indexOf(child.tagName) != -1) {
            copyStylesInline(child, sourceNode.childNodes[cd]);
            continue;
       }
       var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
       if (style == "undefined" || style == null) continue;
       for (var st = 0; st < style.length; st++){
            child.style.setProperty(style[st], style.getPropertyValue(style[st]));
       }
   }
}

function triggerDownload (imgURI, fileName) {
  var evt = new MouseEvent("click", {
    view: window,
    bubbles: false,
    cancelable: true
  });
  var a = document.createElement("a");
  a.setAttribute("download", fileName);
  a.setAttribute("href", imgURI);
  a.setAttribute("target", '_blank');
  a.dispatchEvent(evt);
}

function downloadSvg(svg, fileName) {
  var copy = svg.cloneNode(true);
  copyStylesInline(copy, svg);
  var canvas = document.createElement("canvas");
  var bbox = svg.getBBox();
  canvas.width = bbox.width;
  canvas.height = bbox.height;
  var ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, bbox.width, bbox.height);
  var data = (new XMLSerializer()).serializeToString(copy);
  var DOMURL = window.URL || window.webkitURL || window;
  var img = new Image();
  var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
  var url = DOMURL.createObjectURL(svgBlob);
  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
    if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
    {
        var blob = canvas.msToBlob();         
        navigator.msSaveOrOpenBlob(blob, fileName);
    } 
    else {
        var imgURI = canvas
            .toDataURL("image/png")
            .replace("image/png", "image/octet-stream");
        triggerDownload(imgURI, fileName);
    }
    document.removeChild(canvas);
  };
  img.src = url;
}

其他回答

这是一个老问题,在2022年我们有ES6,我们不需要第三方库。

下面是将svg图像转换为其他格式的一种非常基本的方法。

诀窍是将svg元素作为img元素加载,然后使用canvas元素将图像转换为所需的格式。因此,需要四个步骤:

提取svg作为xml数据字符串。 将xml数据字符串加载到img元素中 使用canvas元素将img元素转换为dataURL 将转换后的dataURL加载到新的img元素中

步骤1

提取svg as xml数据字符串很简单,我们不需要将其转换为base64字符串。我们只是将其序列化为XML,然后将字符串编码为URI:

// Select the element:
const $svg = document.getElementById('svg-container').querySelector('svg')

// Serialize it as xml string:
const svgAsXML = (new XMLSerializer()).serializeToString($svg)

// Encode it as a data string:
const svgData = `data:image/svg+xml,${encodeURIComponent(svgAsXML)}`

步骤2

将xml数据字符串加载到img元素中:

// This function returns a Promise whenever the $img is loaded
const loadImage = async url => {
    const $img = document.createElement('img')
    $img.src = url
    return new Promise((resolve, reject) => {
        $img.onload = () => resolve($img)
        $img.onerror = reject
        $img.src = url
    })
}

步骤3

使用canvas元素将img元素转换为dataURL:

const $canvas = document.createElement('canvas')
$canvas.width = $svg.clientWidth
$canvas.height = $svg.clientHeight
$canvas.getContext('2d').drawImage(img, 0, 0, $svg.clientWidth, $svg.clientHeight)
return $canvas.toDataURL(`image/${format}`, 1.0)

步骤4

将转换后的dataURL加载到新的img元素中:

const $img = document.createElement('img')
$img.src = dataURL
$holder.appendChild($img)

这里你有一个工作片段:

const $svg = document.getElementById('svg-container').querySelector('svg') const $holder = document.getElementById('img-container') const $label = document.getElementById('img-format') const destroyChildren = $element => { while ($element.firstChild) { const $lastChild = $element.lastChild ?? false if ($lastChild) $element.removeChild($lastChild) } } const loadImage = async url => { const $img = document.createElement('img') $img.src = url return new Promise((resolve, reject) => { $img.onload = () => resolve($img) $img.onerror = reject }) } const convertSVGtoImg = async e => { const $btn = e.target const format = $btn.dataset.format ?? 'png' $label.textContent = format destroyChildren($holder) const svgAsXML = (new XMLSerializer()).serializeToString($svg) const svgData = `data:image/svg+xml,${encodeURIComponent(svgAsXML)}` const img = await loadImage(svgData) const $canvas = document.createElement('canvas') $canvas.width = $svg.clientWidth $canvas.height = $svg.clientHeight $canvas.getContext('2d').drawImage(img, 0, 0, $svg.clientWidth, $svg.clientHeight) const dataURL = await $canvas.toDataURL(`image/${format}`, 1.0) console.log(dataURL) const $img = document.createElement('img') $img.src = dataURL $holder.appendChild($img) } const buttons = [...document.querySelectorAll('[data-format]')] for (const $btn of buttons) { $btn.onclick = convertSVGtoImg } .wrapper { display: flex; flex-flow: row nowrap; width: 100vw; } .images { display: flex; flex-flow: row nowrap; width: 70%; } .image { width: 50%; display: flex; flex-flow: row wrap; justify-content: center; } .label { width: 100%; text-align: center; } <div class="wrapper"> <div class="item images"> <div class="image left"> <div class="label">svg</div> <div id="svg-container"> <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="200" height="200" viewBox="0 0 248 204"> <path fill="#1d9bf0" d="M221.95 51.29c.15 2.17.15 4.34.15 6.53 0 66.73-50.8 143.69-143.69 143.69v-.04c-27.44.04-54.31-7.82-77.41-22.64 3.99.48 8 .72 12.02.73 22.74.02 44.83-7.61 62.72-21.66-21.61-.41-40.56-14.5-47.18-35.07 7.57 1.46 15.37 1.16 22.8-.87-23.56-4.76-40.51-25.46-40.51-49.5v-.64c7.02 3.91 14.88 6.08 22.92 6.32C11.58 63.31 4.74 33.79 18.14 10.71c25.64 31.55 63.47 50.73 104.08 52.76-4.07-17.54 1.49-35.92 14.61-48.25 20.34-19.12 52.33-18.14 71.45 2.19 11.31-2.23 22.15-6.38 32.07-12.26-3.77 11.69-11.66 21.62-22.2 27.93 10.01-1.18 19.79-3.86 29-7.95-6.78 10.16-15.32 19.01-25.2 26.16z"/> </svg> </div> </div> <div class="image right"> <div id="img-format" class="label"></div> <div id="img-container"></div> </div> </div> <div class="item buttons"> <button id="btn-png" data-format="png">PNG</button> <button id="btn-jpg" data-format="jpeg">JPG</button> <button id="btn-webp" data-format="webp">WEBP</button> </div> </div>

更改SVG以匹配您的元素

function svg2img(){
    var svg = document.querySelector('svg');
    var xml = new XMLSerializer().serializeToString(svg);
    var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
    var b64start = 'data:image/svg+xml;base64,';
    var image64 = b64start + svg64;
    return image64;
};svg2img()

下面是你如何通过JavaScript来做到这一点:

使用Canvas JavaScript库渲染SVG图像:https://github.com/gabelerner/canvg 根据以下说明,从画布中捕获编码为JPG(或PNG)的数据URI:

使用Canvg库有几种方法将SVG转换为PNG。

在我的例子中,我需要从内联SVG中获取PNG blob。

库文档提供了一个示例(参见OffscreenCanvas示例)。

但是这个方法目前在Firefox中不起作用。是的,你可以在设置中启用gfx. offscreenvas .enabled选项。但是网站上的每个用户都会这么做吗?:)

然而,还有另一种方法也适用于Firefox。

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

最后一行多亏了这个答案

下面是一个函数,它在没有库的情况下工作,并返回一个Promise:

/**
 * converts a base64 encoded data url SVG image to a PNG image
 * @param originalBase64 data url of svg image
 * @param width target width in pixel of PNG image
 * @return {Promise<String>} resolves to png data url of the image
 */
function base64SvgToBase64Png (originalBase64, width) {
    return new Promise(resolve => {
        let img = document.createElement('img');
        img.onload = function () {
            document.body.appendChild(img);
            let canvas = document.createElement("canvas");
            let ratio = (img.clientWidth / img.clientHeight) || 1;
            document.body.removeChild(img);
            canvas.width = width;
            canvas.height = width / ratio;
            let ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            try {
                let data = canvas.toDataURL('image/png');
                resolve(data);
            } catch (e) {
                resolve(null);
            }
        };
        img.onerror = function() {
            resolve(null);
        };
        img.src = originalBase64;
    });
}

在Firefox上,svg没有设置宽度/高度是有问题的。

请参阅此工作示例,其中包括Firefox问题的修复。