LoginSignup
7

More than 3 years have passed since last update.

要素の重なりを判定する関数を作ってみた

Last updated at Posted at 2018-02-28

概要

  1. 要素の絶対座標と長さを計算し、JSONオブジェクトでまとめる。

  2. 1.で生成した2つのJSONオブジェクトから以下の(1),(2)の条件を判定する。
    (1)要素1の右端より要素2の左端が左側にあり、要素1の左端より要素2の左端が右側にあれば、横方向に重なっている。
    (2)要素1の下端より要素2の上端が上側にあり、要素1の上端より要素2の上端が下側にあれば、縦方向に重なっている。

  3. (1)と(2)を満たす場合は、trueを返す。そうでなければ、falseを返す。

ソースコード

/**
 * @param rect1
 * @param rect2
 * @return boolean
 */
function detectCollision(rect1, rect2) {
    if( ( ( rect1.xStart <= rect2.xStart && rect2.xStart <= rect1.xEnd ) ||
          ( rect1.xStart <= rect2.xEnd && rect2.xEnd <= rect1.xEnd ) ) &&
        ( ( rect1.yStart <= rect2.yStart && rect2.yStart <= rect1.yEnd ) ||
          ( rect1.yStart <= rect2.yEnd && rect2.yEnd <= rect1.yEnd ) )
    ) {
        return true;
    } else {
        return false;
    }
}
/**
 * @param e Element
 * @return Object
 */
function createBoundingClientRect(e) {
    var x = (window.pageXOffset !== undefined)
        ? window.pageXOffset
        : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
    var y = (window.pageYOffset !== undefined)
        ? window.pageYOffset
        : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    var rect = e.getBoundingClientRect();
    var width = rect.width;
    var height = rect.height;
    var xStart = rect.left + x;
    var xEnd = xStart + width;
    var yStart = rect.top + y;
    var yEnd = yStart + height;
    return {
        rect: rect,
        width: width,
        height: height,
        xStart: xStart,
        xEnd: xEnd,
        yStart: yStart,
        yEnd: yEnd
    };
}

使い方

var sun = document.querySelector('#sun');
var moon = document.querySelector('#moon');
var sunRect = createBoundingClientRect(sun);
var moonRect = createBoundingClientRect(moon);
if( detectCollision(sunRect, moonRect) ){
    alert('Eclipse!');
}

参考

window.scrollY
JavaScriptでスクロール量を取得する

追記

2018/03/01 13:56 関数名を変更 checkOverlap -> detectCollision
コメントありがとうございました。Collisionが感覚的にGoodだったので、採用しました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7