Greasy Fork

Greasy Fork is available in English.

SVG2PNG

svg转png

目前为 2024-08-10 提交的版本,查看 最新版本

// ==UserScript==
// @name         SVG2PNG
// @namespace    https://www.processon.com/
// @version      0.1
// @description  svg转png
// @author       You
// @match        https://www.processon.com/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=https://www.processon.com/
// @grant        none
// @license      MIT
// ==/UserScript==
 
(function() {
    'use strict';
 
    // Your code here...
    try {
    // 获取特定 class 名的 <div> 中的第一个 <svg> 标签
    const divElement = document.querySelector('.water_perview');
    const svgElement = divElement.querySelector('svg');

    // 获取 SVG 的宽度和高度属性
    const width = parseInt(svgElement.getAttribute('width'));
    const height = parseInt(svgElement.getAttribute('height'));

    // 创建一个 Canvas 元素
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    // 获取 Canvas 的 2D 渲染上下文
    const ctx = canvas.getContext('2d');

    // 将 SVG 内容序列化为字符串
    const svgData = new XMLSerializer().serializeToString(svgElement);

    // 将 SVG 字符串转换为一个 Blob 对象
    const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });

    // 使用 FileReader 将 SVG Blob 读取为 Data URL
    const reader = new FileReader();
    reader.readAsDataURL(svgBlob);

    reader.onload = function(event) {
        const img = new Image();
        img.onload = function() {
            // 将 SVG 图像绘制到 Canvas 上
            ctx.drawImage(img, 0, 0);

            // 将 Canvas 导出为 PNG 数据 URL
            const pngData = canvas.toDataURL('image/png');

            // 创建一个下载链接
            const link = document.createElement('a');
            link.href = pngData;
            link.download = 'image.png';
            link.click();
        };
        img.src = event.target.result;
    };
} catch (error) {
    console.error('Error converting SVG to PNG:', error);
}
 
})();