user2284433
user2284433

Reputation:

HTML 5 Canvas, interact with HTML tags behind it?

Ok, so I have a HTML 5 canvas element on top of my website to overlay a snow effect.

I use this CSS to get the snow effect on top of the rest of the website:

#snow {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none;
}

What I'd like to do is get the snow interacting with elements on the page. e.g. If it hits a <p> tag, it will stop. So the snow gradually builds up on elements on the page.

How would I go about doing this? How do you get the locations of elements on a different layer with Javascript?

Upvotes: 0

Views: 467

Answers (1)

user1693593
user1693593

Reputation:

The principle is fairly straight-forwards.

  • Collect the elements you want to interact with
  • Extract the client-rect of each which represents each element's absolute position
  • Update on scroll etc.

DEMO

In this demo the red squares representing DOM elements are drawn on the canvas, not set by CSS. This to demonstrate the principle. What you can do with the code is to use these rectangles as collision objects instead with the snow.

Get the elements we want to interact with:

var elements = document.querySelectorAll('p'); /// all "P" elements

Now iterate through the collection and get the absolute boundary rectangle from each:

function getRects() {
    
    for(var i = 0; i < elements.length; i++) {

        /// get rect for this element
        rect = elements[i].getBoundingClientRect();
        
        /// use it for something, or store in an array etc.
        ctx.strokeRect(rect.left,
                       rect.top,
                       rect.width,
                       rect.height);
    }
}

(sorry, no snow demo but you should be able to use this to implement what you ask for).

Upvotes: 1

Related Questions