Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - Compute real size of svg considering stroke and transformations

I have an svg element and I need to compute the real size of the element.

For example consider this:

<g>
   <path d="M 0 0 L 20 0" symbol-local-id="42a57c74-adcf-480a-b193-572a1c50a7a1" fill="none" stroke="#666666" stroke-width="3" stroke-miterlimit="10" stroke-linecap="flat" pointer-events="all"/>
</g>

The expected size should be width:20px and height:3px

The SVG can be much more complicated than this, so I need to compute it dynamically.

I can't use getBBox() nor getBoundingClientRect() because they compute size without considering stroke.

So I tried to render it in a canvas and count the number of pixels to get the real size, but things don't work I continue to get height 1px.

This is the algorithm to compute the size:

const rasterSVGAndGetRealSize = function (svgEl, renderedCallback) {

    svgEl.removeAttribute('viewBox');
    svgEl.removeAttribute('width');
    svgEl.removeAttribute('height');
    svgEl.style.backgroundColor = 'rgba(255, 255, 255, 1)';

    const style = document.createElement('style');
    style.innerHTML = 'path, text, rect, ellipse { fill: rgba(0,0,0,1) !important; stroke: rgba(0,0,0,1)!important}';
    svgEl.insertBefore(style, svgEl.firstChild);

    const serialized = new XMLSerializer().serializeToString(svgEl);
    const uri = 'data:image/svg+xml;base64,' + window.btoa(serialized);

    // load svg image into canvas
    const image = new Image();
    image.onload = function () {
        const canvas = document.createElement('canvas');
        const w = image.naturalWidth;
        const h = image.naturalHeight;
        canvas.width = w;
        canvas.height = h;
        const context = canvas.getContext('2d');
        
        context.drawImage(image, 0, 0);
        const imageData = context.getImageData(0, 0, w, h);
        const data = imageData.data;
        let left = w;
        let top = h;
        let right = 0;
        let bottom = 0;
        for (let r = 0; r < h; r++) {
            for (let c = 0; c < w; c++) {
                const pixel = w * r + c;
                const red = data[4 * pixel];
                const green = data[4 * pixel + 1];
                const blue = data[4 * pixel + 2];
                const alpha = data[4 * pixel + 3];
                if (red !== 255 || green !== 255 || blue !== 255) {
                    if (c < left) {
                        left = c;
                    }
                    if (r < top) {
                        top = r;
                    }
                    if (c > right) {
                        right = c;
                    }
                    if (r > bottom) {
                        bottom = r;
                    }
                }
            }
        }
        renderedCallback({ left: left, top: top, right: right, bottom: bottom, width: right - left + 1, height: bottom - top + 1 });
        //canvas.setAttribute('id', 'imageTest');
        //document.body.appendChild(canvas);
    }
    image.src = uri;
};

What is wrong? Do you know another solution to compute the real size of the SVG?

Check this fiddle: https://jsfiddle.net/orbintsoft/jo17fkgr/5/

question from:https://stackoverflow.com/questions/65830123/compute-real-size-of-svg-considering-stroke-and-transformations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only solution that I found is to overestimate the size of the SVG, and translate all elements inside.
Another important thing is to disable antialiasing with crispedges.
To avoid problems with null pixel and unwanted antialiased pixels, I set 2 very distant colors, but different from black and white.

Here my solution:

(function(global) {
    global.ComputeBoundingBox = {
        rasterSVGAndGetRealBoundingBox : function (svgEl, overEstimatedWidth, overEstimatedHeight, leftOffset = 50, topOffset = 50) {
            return new Promise(resolve => {
                let svgRoot = null;
                if (svgEl.tagName === 'svg') {
                    svgRoot = svgEl;
                } else {
                    svgRoot = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                    svgRoot.appendChild(svgEl);
                }
                svgRoot.setAttribute('viewBox', `0 0 ${overEstimatedWidth} ${overEstimatedHeight}`);
                svgRoot.removeAttribute('width', `${overEstimatedWidth}px`);
                svgRoot.removeAttribute('height', `${overEstimatedHeight}px`);
                svgRoot.style.backgroundColor = 'rgba(240,240,240, 1)';

                const style = document.createElement('style');
                style.innerHTML = 'path, text, rect, ellipse { fill: rgba(10,10,10,1) !important; stroke: rgba(10,10,10,1)!important; shape-rendering: crispEdges !important; }';
                svgRoot.insertBefore(style, svgRoot.firstChild);

                for (let el of svgRoot.childNodes) {
                    if (el.tagName === 'g' || el.tagName === 'rect' || el.tagName === 'path' || el.tagName === 'text' || el.tagName === 'ellipse' || el.tagName === 'circle' || el.tagName === 'line' || el.tagName === 'polyline' || el.tagName === 'polygon') {
                        const cloned = el.cloneNode(true);
                        const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
                        g.appendChild(cloned);
                        el.replaceWith(g);
                        g.style.transform = `translate(${leftOffset}px, ${topOffset}px)`;
                        g.style.transformOrigin = 'center';
                        g.style.transformBox = 'fillBox';
                    }
                }


                const serialized = new XMLSerializer().serializeToString(svgRoot);
                const uri = 'data:image/svg+xml;base64,' + window.btoa(serialized);
                // load svg image into canvas
                const image = new Image();
                image.onload = function () {
                    const canvas = document.createElement('canvas');
                    let w = overEstimatedWidth;
                    let h = overEstimatedHeight;
                    canvas.width = w;
                    canvas.height = h;
                    const context = canvas.getContext('2d');
                    context.drawImage(image, 0, 0);

                    const imageData = context.getImageData(0, 0, w, h);
                    const data = imageData.data;
                    let left = w;
                    let top = h;
                    let right = 0;
                    let bottom = 0;
                    for (let r = 0; r < h; r++) {
                        for (let c = 0; c < w; c++) {
                            const pixel = w * r + c;
                            const red = data[4 * pixel];
                            const green = data[4 * pixel + 1];
                            const blue = data[4 * pixel + 2];
                            const alpha = data[4 * pixel + 3];
                            if ((red === 10) || (green === 10) || (blue === 10)) {
                                if (c < left) {
                                    left = c;
                                }
                                if (r < top) {
                                    top = r;
                                }
                                if (c > right) {
                                    right = c;
                                }
                                if (r > bottom) {
                                    bottom = r;
                                }
                            }
                        }
                    }
                    left -= leftOffset;
                    right = right - leftOffset + 1;
                    top -= topOffset;
                    bottom = bottom - topOffset + 1;
                    resolve({ left: left, top: top, right: right, bottom: bottom, width: right - left, height: bottom - top });
                }
                image.src = uri;
            });
        }
    }
})(window);



const svg = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet"><g><path d="M 0 0 L 20 0" fill="none" stroke="#666666" stroke-width="3"/></g></svg>';

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(svg,"image/svg+xml");
const root = xmlDoc.getElementsByTagName('svg')[0];

const promise = ComputeBoundingBox.rasterSVGAndGetRealBoundingBox(root, 1000, 1000);
promise.then((size) => {console.dir(size);});

https://jsfiddle.net/54yvjhwt/1/

Since this solution involves many contraints, I hope someone will be able to improve and provide a better solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...