loktar00 / JQuery-Snowfall

Makes it snow on any web page or specific element.
http://loktar00.github.io/JQuery-Snowfall/
712 stars 221 forks source link

Canvas Offset Misplaced #9

Open mannybiker opened 11 years ago

mannybiker commented 11 years ago

There is an error in the offset of the collection canvas if you hava a page that is longer then the screen size so that scroll bar are activated and you make a page refresh when the scroll bar is not at the top position. I can reproduce this problem on your test index.html page with FF17. Strangely its seems to work on IE9 with your test page but I have the issue when I use your script on other sites.

In my opinion the problem is related to the getBoundingClientRect() that return the coordinates given relative to window and not to the document. Maybe there is a smarter way to fix this but I've corrected the script in this way:

Adding this function:

function getOffsetRect(elem) {
    var box = elem.getBoundingClientRect()
    var body = document.body
    var docElem = document.documentElement
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0
    var top  = box.top +  scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft
    return { top: Math.round(top), left: Math.round(left), width: box.width }
}

and using this instead of elements[i].getBoundingClientRect():

var bounds = getOffsetRect(elements[i])

Hope this help!