hw_22_04_rgb.html 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <header></header>
  2. <body>
  3. <script>
  4. class RGB {
  5. #r = 0
  6. #g = 0
  7. #b = 0
  8. checkChannelValue(val) {
  9. val = +val
  10. if (typeof val !== "number" || val < 0 || val > 255) {
  11. throw new Error(`invalid channel value: ${val}`)
  12. }
  13. }
  14. get r() {
  15. return this.#r;
  16. }
  17. set r(val) {
  18. this.checkChannelValue(val);
  19. this.#r = +val;
  20. }
  21. get g() {
  22. return this.#g;
  23. }
  24. set g(val) {
  25. this.checkChannelValue(val);
  26. this.#g = +val;
  27. }
  28. get b() {
  29. return this.#b;
  30. }
  31. set b(val) {
  32. this.checkChannelValue(val);
  33. this.#b = +val;
  34. }
  35. set hex(val) {
  36. let matchColors = /^#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/;
  37. let match = matchColors.exec(val);
  38. if (match !== null && match.length == 4) {
  39. this.r = parseInt(`${match[1]}`, 16);
  40. this.g = parseInt(`${match[2]}`, 16);
  41. this.b = parseInt(`${match[3]}`, 16);
  42. return;
  43. }
  44. throw new Error(`incorrect hex color parameter: ${val}`);
  45. }
  46. get hex() {
  47. return `#${this.r.toString(16).toUpperCase()}${this.g.toString(16).toUpperCase()}${this.b.toString(16).toUpperCase()}`;
  48. }
  49. set rgb(val) {
  50. let matchColors = /^rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)$/;
  51. let match = matchColors.exec(val);
  52. if (match !== null && match.length == 3) {
  53. this.r = match[1];
  54. this.g = match[2];
  55. this.b = match[3];
  56. return;
  57. }
  58. throw new Error(`incorrect rgb color parameter: ${val}`);
  59. }
  60. get rgb() {
  61. return `rgb(${this.r}, ${this.g}, ${this.b})`;
  62. }
  63. /* constructor(r, g, b) {
  64. this.r = r;
  65. this.g = g;
  66. this.b = b;
  67. }*/
  68. constructor(colorString) {
  69. if (colorString.startsWith("#"))
  70. this.hex = colorString;
  71. else
  72. this.rgb = colorString;
  73. }
  74. }
  75. function assertAreEqual(actual, expected) {
  76. if (actual != expected)
  77. throw new Error(`not expected value. actual: ${actual}, expected: ${expected}`);
  78. }
  79. //let color = new RGB('#AABBFF');
  80. //assertAreEqual(color.hex, '#AABBFF');
  81. let color = new RGB ('rgb(55, 49, 121)');
  82. assertAreEqual(color.rgb, ('55, 49, 121'));
  83. assertAreEqual(color.hex, `#373179`);
  84. //*color.rgb = `rgb(55, 49, 121)`;
  85. //assertAreEqual(color.r, 55);
  86. //assertAreEqual(color.g, 49);
  87. // assertAreEqual(color.b, 121);
  88. //assertAreEqual(color.rgb, `rgb(55, 49, 121)`);
  89. //assertAreEqual(color.hex, `#373179`);
  90. </script>
  91. </body>