Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Transform SVG relative to viewport

I want to make this SVG clipping-mask transform relatively to browser viewport width and height.

I tried to do this with Javascript, where I check for the position of SVG relative to window and the viewport value (vw,vh). I want the space between SVG and right side of viewport always be a certain value.

However, the code below runs only once whenever position of SVG is smaller than vw - 100. Even after being "translated", the top and left value of SVG stays the same. So what is a possible solution for this issue?

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

const svg = document.getElementById('black-hole')

var viewportOffset = svg.getBoundingClientRect();
var top = viewportOffset.top;
var left = viewportOffset.left;

if (left > (vw - 100))
{
  svg.style.transform = "translate(" + (left - 200) + "px,"+ top + "px)";
}
.red
{
    clip-path: url(#myClip);
    width: 100vw;
    height:100vh;
    background-color: red;
    background-image: url(./img/project.jpg);
    background-size: cover;
    position:absolute;
} 

#black-hole {
    transform-box: fill-box;
    transform: translate(18rem,2rem);
    transform-origin: center;
}
<div class="red"></div>

<svg height="0" width="0">
                <clipPath id="myClip" > 
                    <path id="black-hole" xmlns="http://www.w3.org/2000/svg" class="cls-2" d="M208.5,3.5c-61-4-125,31-141,94-5,19-5,39,4,57-10-48,21-95,64-116,31-15,66-17,99-7,30,9,59,26,77,53-31-33-75-55-121-51-36,3-73,24-86,59,18-27,47-42,79-44a130,130,0,0,1,104,43c31,36,47,85,35,131,10-65-25-138-93-155-19-5-39-5-57,4,48-10,95,21,116,64,15,31,17,66,7,99-9,30-26,59-53,77,33-31,55-75,51-121-3-36-24-73-59-86,27,18,42,47,44,79a130,130,0,0,1-43,104c-36,31-85,47-131,35,65,10,138-25,155-93,5-19,5-39-4-57,10,48-21,95-64,116-31,15-66,17-99,7-30-9-59-26-77-53,31,33,75,55,121,51,36-3,73-24,86-59-18,27-47,42-79,44a130,130,0,0,1-104-43c-31-36-47-85-35-131-10,65,25,138,93,155,19,5,39,5,57-4-48,10-95-21-116-64-15-31-17-66-7-99,9-30,26-59,53-77-33,31-55,75-51,121,3,36,24,73,59,86-27-18-42-47-44-79a130,130,0,0,1,43-104c36-31,85-47,131-35a66,66,0,0,1-14-1Z"/>
                </clipPath>
            </svg>

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

1 Answer

0 votes
by (71.8m points)

Have you tried using calc() in css? It will do a little math for you without JavaScript. So your width would be:

width: calc(100vw - 10px) 

The 10px represents whatever specific space you were looking for.

Here's the MDN info


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...