概要
この記事では、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