3
1

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】HSL⇔HSY色空間変換クラス

Last updated at Posted at 2018-04-03

#概要
この記事は、Javascriptを用いたHSL⇔HSY色空間の変換式を紹介しています。導入式の理論や説明はこちらからご覧ください。また、前回のRGB⇔HSL色空間変換クラスを前提として実装しておりますので、そちらもご参照ください。

#コード

HSYColorSpace.js
class HSYColorSpace extends HSLColorSpace {
	constructor(r, g, b) {
		super(r, g, b);
		this.isHoldY = false; // public
	}
	initialize() {// @Override
		this._y = new Range(0);// contrast
		super.initialize();
	}
	static get _pr() {
		return 0.298912;
	}
	static get _pg() {
		return 0.586611;
	}
	static get _pb() {
		return 0.114478;
	}
	get y() {
		return this._y.get();
	}
	set y(newValue) {
		this._y.set(newValue);
		this.transformLuminosityFromContrast();
		this.inverseTransformation();
	}
	get l() {// setterとgetterはセットでOverrideしなければならない
		return super.l;
	}
	set l(newValue) {// @Override
		this._l.set(newValue);
		this.transformContrastFromLuminosity();
		super.inverseTransformation();
	}
	transformation() {// @Override
		super.transformation();
		this.transformContrastFromLuminosity();
	}
	inverseTransformation() {// @Override
		if(this.isHoldY)
			this.transformLuminosityFromContrast();
		else
			this.transformContrastFromLuminosity();
		
		super.inverseTransformation();
	}
	transformContrastFromLuminosity() {
		let c = this._coef;
		let l = this._l.get();
		
		if(this._l.isOver(0.5))
			this._y.set(l * (1 + c) - c);
		else
			this._y.set(l * (1 - c));
	}
	transformLuminosityFromContrast() {
		let c = this._coef;
		let y = this._y.get();
		
		if(this._y.isOver((1 - c) / 2))
			this._l.set((y + c) / (1 + c));
		else
			this._l.set(y / (1 - c));
	}
	get _pure() { // PureColorContrast: 純色(s = 1.0, l = 0.5)のコントラストy
		const self = HSYColorSpace;
		const pr = self._pr, pg = self._pg, pb = self._pb;
		const pmax = [pr,pg,pg,pb,pb,pr];
		const pmid = [pg,pr,pb,pg,pr,pb];
		//const pmin = [pb,pb,pr,pr,pg,pg];
		let i = this._h.interval;
		return pmax[i] + this._h.different * pmid[i];
	}
	get _coef() { // 計算を簡単に表記するための定数
		return this.s * (1 - 2 * this._pure); // S * 2 * (0.5 - pure)
	}
	static calc(r, g, b) {
		const self = HSYColorSpace;
		const pr = self._pr, pg = self._pg, pb = self._pb;
		return pr * r + pg * g + pb * b;
	}
}

コメントにも書いてありますが、プロパティ(getterとsetter)をOverrideする場合は、両方をOverrideする必要があります。片方、例えばsetterだけOverrideすると、getterは使用できなくなります。結果、getterの戻り値はundefinedとなります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?