Safari is not respecting scaling applied to a foreignObject

前端 未结 2 1913
执念已碎
执念已碎 2021-01-12 04:42

The following is a strange, and clearly buggy behavior of Safari (tested with versions 11 & 12). A containing HTML, when scaled, still

相关标签:
2条回答
  • 2021-01-12 04:45

    This seems to be related to webkit bug 23113. The only workaround I've found so far is adding a CSS transform: scale(${scale}) (where you'd have to get the current scale using JS) property to a <section> inside foreignObject (an example can be found in marpit-svg-polyfill)

    0 讨论(0)
  • 2021-01-12 04:49

    I couldn't think of any decent solution either, so I came up with a little hacky approach - you need to place the svg into the container, then get the width of the container and width of the svg, scale accordingly and position it properly:

    if (window['safari'] !== undefined) {
        const svgContainerElement = document.getElementById('svgContainer');
        const svgElement = document.getElementById('svg');
    
        const zoomLevel = svgContainerElement.clientWidth / 867; // width of the foreign object
        svgElement.style.transform = `scale(${zoomLevel})`;
    
        const leftOffset = svgContainerElement.getBoundingClientRect().left - 
        svgElement.getBoundingClientRect().left;
        const topOffset = svgContainerElement.getBoundingClientRect().top - 
    svgElement.getBoundingClientRect().top;
    
        svgElement.style.position = `relative`;
        svgElement.style.left = leftOffset;
        svgElement.style.top = topOffset;
    }
    

    you may be forced to re-draw the svg if the browser doesn't react to the style changes properly:

    const parent = svgElement.parentElement;
    if (parent) {
        parent.removeChild(el);
        parent.appendChild(el);
    }
    

    It may be like a few years late to this question, but I hope it will help somebody since this is a problem in safari to this date (November 2019)

    0 讨论(0)
提交回复
热议问题