Search code examples
javascripthtmlcssclipclip-path

Use a moving div as a CSS clip path


I cannot seem to find a similar question out there in Google nor Stack Overflow. Here is my situation.

I have a div being used for a background image. I want this image to be hidden except for what is behind a second div that moves around with the mouse.

The moving div is a 250px by 250px circle like this.

<div class="page-mouse-tail"></div>
<style>
.page-mouse-tail {
    position: fixed;
    float: left;
    width: 250px;
    height: 250px;
    border-radius: 100%;
}
</style>

I move that div around using this Javascript:

"use strict";
var mouseTails = document.getElementsByClassName("page-mouse-tail");
document.addEventListener("mousemove", function (event) {
    Array.prototype.forEach.call(mouseTails, function (tail) {
        tail.style.left = event.pageX + "px";
        tail.style.top = event.pageY + "px";
    });
});

Is there anyway I can make it so the background-image div can only be seen by what is "underneath" the mouse-tail div? Like a clip-path that is a circle, but moves with the mouse. I would like to only use CSS and Javascript, if possible. Thank you.


Solution

  • You can add this to the second div's style:

    overflow: hidden;