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


当前回答

这是一个老问题,在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数据,这个ES6类做了这项工作。

class SvgToPngConverter {
  constructor() {
    this._init = this._init.bind(this);
    this._cleanUp = this._cleanUp.bind(this);
    this.convertFromInput = this.convertFromInput.bind(this);
  }

  _init() {
    this.canvas = document.createElement("canvas");
    this.imgPreview = document.createElement("img");
    this.imgPreview.style = "position: absolute; top: -9999px";

    document.body.appendChild(this.imgPreview);
    this.canvasCtx = this.canvas.getContext("2d");
  }

  _cleanUp() {
    document.body.removeChild(this.imgPreview);
  }

  convertFromInput(input, callback) {
    this._init();
    let _this = this;
    this.imgPreview.onload = function() {
      const img = new Image();
      _this.canvas.width = _this.imgPreview.clientWidth;
      _this.canvas.height = _this.imgPreview.clientHeight;
      img.crossOrigin = "anonymous";
      img.src = _this.imgPreview.src;
      img.onload = function() {
        _this.canvasCtx.drawImage(img, 0, 0);
        let imgData = _this.canvas.toDataURL("image/png");
        if(typeof callback == "function"){
            callback(imgData)
        }
        _this._cleanUp();
      };
    };

    this.imgPreview.src = input;
  }
}

下面是你如何使用它

let input = "https://restcountries.eu/data/afg.svg"
new SvgToPngConverter().convertFromInput(input, function(imgData){
    // You now have your png data in base64 (imgData). 
    // Do what ever you wish with it here.
});

如果你想要一个普通的JavaScript版本,你可以访问Babel网站并在那里编译代码。

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

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

更改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()

Jbeard4解决方案工作得很好。

我使用Raphael SketchPad创建SVG。链接到步骤1中的文件。

对于保存按钮(svg的id是"editor", canvas的id是"canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});

这是我的2美分。不知怎的,下载锚标签在代码片段中不像预期的那样工作,但在Chrome中工作得很好。

这里正在使用jsFiddle

const waitForImage = imgElem => new Promise(resolve => imgElem.complete ? resolve() : imgElem.onload = imgElem.onerror = resolve); const svgToImgDownload = ext => { if (!['png', 'jpg', 'webp'].includes(ext)) return; const _svg = document.querySelector("#svg_container").querySelector('svg'); const xmlSerializer = new XMLSerializer(); let _svgStr = xmlSerializer.serializeToString(_svg); const img = document.createElement('img'); img.src = 'data:image/svg+xml;base64,' + window.btoa(_svgStr); waitForImage(img) .then(_ => { 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/' + (ext == 'jpg' ? 'jpeg' : ext), 1.0); }) .then(dataURL => { console.log(dataURL); document.querySelector("#img_download_btn").innerHTML = `<a href="${dataURL}" download="img.${ext}">Download</a>`; }) .catch(console.error); }; document.querySelector('#map2Png').addEventListener('click', _ => svgToImgDownload('png')); document.querySelector('#map2Jpg').addEventListener('click', _ => svgToImgDownload('jpg')); document.querySelector('#map2Webp').addEventListener('click', _ => svgToImgDownload('webp')); <div id="svg_container" style="float: left; width: 50%"> <svg width="200" height="200" viewBox="-100 -100 200 200"> <circle cx="0" cy="20" r="70" fill="#D1495B" /> <circle cx="0" cy="-75" r="12" fill="none" stroke="#F79257" stroke-width="2" /> <rect x="-17.5" y="-65" width="35" height="20" fill="#F79257" /> </svg> </div> <div> <button id="map2Png">PNG</button> <button id="map2Jpg">JPG</button> <button id="map2Webp">WEBP</button> </div> <div id="img_download_btn"></div>