main.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. function Control(el, {
  2. value = 0,
  3. min = 0,
  4. max = 255,
  5. minAngle = 0,
  6. maxAngle = 360,
  7. wheelSpeed = 0.1,
  8. step = 1
  9. } = {}) {
  10. const img = document.createElement('img')
  11. img.src = '1@3x.png';
  12. el.append(img);
  13. const ratio = (maxAngle - minAngle) / (max - min)
  14. const getAngle = () => (value - min)*ratio + minAngle;
  15. this.setValue = newValue => {
  16. if (newValue > max){
  17. newValue = max
  18. }
  19. if (newValue < min){
  20. newValue = min
  21. }
  22. value = newValue
  23. img.style.transform = `rotate(${getAngle()}deg)`
  24. }
  25. img.onmousewheel = e => {
  26. const {deltaY} = e
  27. const newValue = value + deltaY*wheelSpeed
  28. this.setValue(newValue)
  29. e.preventDefault()
  30. const colorNum = getAngle();
  31. this.onchange(colorNum);
  32. }
  33. img.onclick = e => {
  34. console.log(e, img.width, e.layerX)
  35. const {layerX} = e
  36. const {width} = img
  37. if (layerX > width/2){
  38. this.setValue(value +step);
  39. }
  40. else {
  41. this.setValue(value -step);
  42. }
  43. const colorNum = getAngle();
  44. this.onchange(colorNum);
  45. }
  46. this.setValue(value);
  47. }
  48. let rgb = {
  49. red: 0,
  50. green: 0,
  51. blue: 0,
  52. }
  53. const volumeControl1 = new Control(container1, {value: 1})
  54. volumeControl1.onchange = function(value) {
  55. rgb.red = value;
  56. document.body.style.backgroundColor = `rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`;
  57. }
  58. const volumeControl2 = new Control(container2, {value: 1})
  59. volumeControl2.onchange = function(value) {
  60. rgb.green = value;
  61. document.body.style.backgroundColor = `rgb(${rgb.red}, ${rgb.green} , ${rgb.blue})`;
  62. }
  63. const volumeControl3 = new Control(container3, {value: 1})
  64. volumeControl3.onchange = function(value) {
  65. rgb.blue = value;
  66. document.body.style.backgroundColor = `rgb(${rgb.red}, ${rgb.green} , ${rgb.blue})`;
  67. }