Blog/etc.
[SVG] clip path
나나 (nykim)
2019. 9. 17. 18:13
320x100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html,
body {
height: 100%;
margin: 0;
}
body {
font-family: Monaco;
font-size: 12px;
color: rgba(0, 0, 0, .7);
}
svg {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: block;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- 기본 이미지 -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="100%" height="100%" fill="#E7E7E8" />
<image id="image" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="./pack1.png" width="100%" height="100%" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<clipPath id="myClipPath">
<circle id="circle" cx="50%" cy="50%" r="10%" style="fill: red" />
<!-- 이 circle 바깥쪽에 있는 건 클립되서 안 보임!! -->
</clipPath>
</defs>
<g clip-path="url(#myClipPath)">
<rect width="100%" height="100%" fill="#272730" />
<image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="./pack2.png" width="100%" height="100%" />
</g>
<circle id="shadow" cx="50%" cy="50%" r="10%"
style="stroke: rgb(183, 113, 240); fill: transparent; stroke-width: 5;" />
</svg>
<script>
var svgElem = document.querySelector("svg");
var maskedElem = document.querySelector("#circle");
var shadow = document.querySelector("#shadow");
var svgPoint = svgElem.createSVGPoint();
function cursorPoint(e) {
svgPoint.x = e.clientX;
svgPoint.y = e.clientY;
return svgPoint;
// return svgPoint.matrixTransform(svgElem.getScreenCTM().inverse());
}
function update(svgCoords) {
maskedElem.setAttribute('cx', svgCoords.x);
maskedElem.setAttribute('cy', svgCoords.y);
shadow.setAttribute('cx', svgCoords.x);
shadow.setAttribute('cy', svgCoords.y);
}
window.addEventListener('mousemove', function (e) {
update(cursorPoint(e));
}, false);
document.addEventListener('touchmove', function (e) {
e.preventDefault();
var touch = e.targetTouches[0];
if (touch) {
update(cursorPoint(touch));
}
}, false);
</script>
</body>
</html>
728x90