Safari is not respecting scaling applied to a foreignObject

前端 未结 2 1912
执念已碎
执念已碎 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: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)

提交回复
热议问题