2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Javascript】要素のクリック位置を取得するクラス

Last updated at Posted at 2018-04-17

概要

この記事では、Javascriptを用いて、要素のクリック位置を取得するクラスを紹介しています。直交座標だけでなく極座標を用いたものもありますので、適宜ご利用ください。

直交座標

Point.js
class Point{
	constructor(x = 0, y = 0) {
		this.x, this.y; // public
		this.set(x, y);
	}
	
	set(x, y) {
		this._x = x;
		this._y = y;
	}

	on(event) {
		const rect = event.target.getBoundingClientRect();
		this.set(
			event.clientX - rect.left,
			event.clientY - rect.top
		);
	}
}

極座標

Angle.java
class Angle{
	constructor(degree = 0) {
		this._degree;
		this.degree = degree;
	}

	set radian(newValue) {
		this.degree = newValue * 180 / Math.PI;
	}

	get radian() {
		return this.degree * Math.PI / 180;
	}

	set degree(newValue) {
		let value = newValue;
		while(value < 0) value += 360;
		value %= 360;
		this._degree = value;
	}

	get degree() {
		return this._degree;
	}
}
Point.java
class Point extends Angle {
	constructor(x = 0, y = 0) {
		super(0);
		this._r;
		this.set(x, y);
	}
	
	get x() {
		return Math.round(this.r * Math.cos(this.radian));
	}
	
	set x(newValue) {
		this.set(newValue, this.y);
	}
	
	get y() {
		return Math.round(this.r * Math.sin(this.radian));
	}
	
	set y(newValue) {
		this.set(this.x, newValue);
	}
	
	get r() {
		return this._r;
	}
	
	set r(newValue) {
		this._r = newValue;
	}
	
	set(x, y) {
		this.r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
		this.radian = Math.atan2(y, x);// arctan
	}

	on(event) {
		const rect = event.target.getBoundingClientRect();
		this.set(
			event.clientX - rect.left,
			event.clientY - rect.top
		);
	}
}

おわりに

私の場合、極座標にも対応できるクラスを用いて、Canvas 要素のクリック位置を取得して、数値を導出したり色調を変更したりしています。
jsファイルにして使いまわすと便利です。

参考資料

https://qiita.com/yukiB/items/31a9e9e600dfb1f34f76
https://qiita.com/yukiB/items/cc533fbbf3bb8372a924

2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?