Replace svg to png

Replace all svg to png

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Replace svg to png
// @version      1.0
// @namespace    svn2png
// @description Replace all svg to png
// @author       muxueqz
// @license      GPL
// @include *://*/*
// @grant       GM_registerMenuCommand
// ==/UserScript==

console.log("svg2png init")

const svg2png_single = (svgString, width, height) => {
  return new Promise((res) => {
    var image = new Image();
    image.src = "data:image/svg+xml," + encodeURIComponent(svgString.outerHTML);
    let url = "";
    image.onload = function() {
      var canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      var context = canvas.getContext("2d");
      context.drawImage(image, 0, 0);
      console.log('width and height:', canvas.width, canvas.height)
      url = canvas.toDataURL("image/" + "png", 1.0);
      res(url);
    };
  });
};

async function svg2png() {
  console.log("svg2png get")
  let svgs = document.querySelectorAll('svg')
  console.log("svg2png svgs", svgs)
  for (const i of svgs) {
    let svg_item = document.getElementById(i.id)
    console.log(svg_item.parentNode)
    var height = svg_item.clientHeight
    var width = svg_item.clientWidth

    let png_b64 = await svg2png_single(svg_item, width, height)
    var new_img = new Image();
    new_img.src = png_b64
    // console.log(new_img)
    let parentNode = (svg_item.parentNode)
    parentNode.append(new_img);
    svg_item.remove()
  }
}

GM_registerMenuCommand("SVG to PNG", svg2png);