I need to get the position of the actual bounding borders of a SVG image after its parent being applied CSS rotation. The grey color in the image below indicates its parent element(In my case it is transparent – I added the grey color in the image below just for indicating the parent element’s border)
getBoundingClientRect() seems to only show the bounding borders of the original rectangle – the red borders shown below. But what I want is the bounding borders without SVG’s transparent background after rotation – like the green borders.
I have tried getBoundingClientRect()
or getBBox()
but they don’t work with rotation being applied.
$('#box').html(svgElement)
$('#box').css({ transform: 'rotate(60deg)' })
svgElement.getBoundingClientRect()
$(function() {
let svgString = '<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 425.58 635.88"><defs><style>.cls-1{fill:#000000;fill-rule:evenodd;}</style></defs><title>1</title><path id="path" class="cls-1" d="M918.94,831.44c-103,110.83-133.9,110.83-236.86,0-68.44-73.68-80.26-150.84-84.92-241.2-4.22-81.95-26.86-194.68,18.05-248.36,70.51-84.25,300.09-84.25,370.59,0,44.92,53.68,22.28,166.41,18.06,248.36C999.2,680.6,987.39,757.77,918.94,831.44Z" transform="translate(-587.72 -278.69)"/></svg>'
let svgElement = new DOMParser().parseFromString(svgString, 'text/xml').documentElement
$('#box').html(svgElement)
$('#box').css({
transform: 'rotate(60deg)'
})
let rect = svgElement.getBoundingClientRect()
$('#bounding-border').css({
left: rect.left + 'px',
top: rect.top + 'px',
width: rect.width + 'px',
height: rect.height + 'px',
})
})
#box {
position: absolute;
left: 100px;
top: 100px;
width: 100px;
height: 150px;
}
svg {
path:hover {
fill: red;
}
}
#bounding-border {
position: absolute;
border: 2px solid red;
z-index: -1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="box"></div>
<div id="bounding-border"></div>