speed.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. function Control(el, {value=0,
  2. min=0,
  3. max=100,
  4. minAngle=0,
  5. maxAngle=360,
  6. wheelSpeed=0.1,
  7. step=1}={}){
  8. const img = document.createElement('img');
  9. img.src = '1@3x.png';
  10. el.append(img);
  11. const ratio = (maxAngle - minAngle) / (max - min);
  12. const getAngle = () => (value - min) * ratio + minAngle;
  13. this.setValue = newValue => {
  14. if (newValue > max){
  15. newValue = max;
  16. }
  17. if (newValue < min){
  18. newValue = min;
  19. }
  20. if(typeof this.onchange === 'function' && newValue !== value){
  21. this.onchange(newValue);
  22. }
  23. value = newValue;
  24. img.style.transform = `rotate(${getAngle()}deg)`;
  25. };
  26. img.onmousewheel = (event) => {
  27. const {deltaY} = event;
  28. this.setValue(value + deltaY * wheelSpeed);
  29. event.preventDefault();
  30. };
  31. img.onclick = (event) => {
  32. const {layerX} = event;
  33. if(layerX < img.width/2){
  34. this.setValue(value - step);
  35. }
  36. else{
  37. this.setValue(value + step);
  38. }
  39. event.preventDefault();
  40. };
  41. const event2Deg = event => {
  42. const {layerX, layerY} = event;
  43. const {width, height} = img;
  44. const x = layerX - width/2;
  45. const y = height/2 - layerY;
  46. return ((Math.atan2(y, x)/ (2 * Math.PI)) * 360 + 360) % 360;
  47. // console.log(x, y, Math.atan2(y, x));
  48. };
  49. let prevAngle = null
  50. img.onmousedown = (event) => {
  51. prevAngle = event2Deg(event);
  52. };
  53. img.onmousemove = (event) => {
  54. if (prevAngle === null) return
  55. const currentAngle = event2Deg(event);
  56. const deltaValue = (prevAngle - currentAngle) / ratio;
  57. // console.log(prevAngle - currentAngle, deltaValue);
  58. this.setValue(value + deltaValue);
  59. prevAngle = currentAngle;
  60. event.preventDefault();
  61. };
  62. img.onmouseup = (event) => {
  63. prevAngle = null;
  64. };
  65. this.setValue(value);
  66. this.getValue = () => value;
  67. }
  68. function setRGB(getValue){
  69. document.body.style.backgroundColor = `rgb(${red.getValue()}, ${green.getValue()}, ${blue.getValue()})`;
  70. }
  71. const red = new Control(container1, {min: 0, max: 255});
  72. red.onchange = setRGB;
  73. const green = new Control(container1, {min: 0, max: 255});
  74. green.onchange = setRGB;
  75. const blue = new Control(container1, {min: 0, max: 255});
  76. blue.onchange = setRGB;
  77. const volumeControl = new Control(volume, {
  78. min: 0,
  79. max: 1,
  80. wheelSpeed: 0.0005,
  81. step: 0.01
  82. });
  83. volumeControl.onchange = setVolume;
  84. function setVolume() {
  85. music.volume = volumeControl.getValue();
  86. }