Griffen
Griffen

Reputation: 427

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.

Upvotes: 2

Views: 619

Answers (2)

Paulie_D
Paulie_D

Reputation: 115288

Yes by applying a giant box-shadow to your "page-tail" div

"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";
  });
});
body {
  background: url(http://wallpaper.ouzs.com/wallpapers/windows_dual_monitor2880x900.jpg);
  background-size: cover;
}
.page-mouse-tail {
  position: fixed;
  float: left;
  width: 150px;
  /* for demo */
  height: 150px;
  border-radius: 100%;
  border: 1px solid red;
  box-shadow: 0 0 0px 9999px white;
}
<div class="page-mouse-tail"></div>

Upvotes: 1

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

overflow: hidden;

Upvotes: 0

Related Questions