Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                

<form>
  <p>Drag and drop control points for addition controls.</p>
  <div class="row">
    <div class="column">
      <div class="input-holder">
        <label>Left Period</label>
        <input class="period" type="range" min="0.5" max="3" value="1" step="0.05" id="left_period"/>
      </div>
      <div class="input-holder">
        <label>Left Amplitude</label>
        <input class="amplitude" type="range" min="10" max="250" value="180" step="5" id="left_amplitude"/>
      </div>
      <div class="input-holder">
        <label>Pendulum Offset</label>
        <input type="range" min="0" max="1" value="0" step="0.02" id="offset"/>
      </div>
    </div>
    <div class="column">
      <div class="input-holder">
        <label>Right Period</label>
        <input class="period" type="range" min="0.5" max="3" value="1.15" step="0.05" id="right_period"/>
      </div>
      <div class="input-holder">
        <label>Right Amplitude</label>
        <input class="amplitude" type="range" min="10" max="250" value="200" step="5" id="right_amplitude"/>
      </div>
      <div class="input-holder">
        <label>Friction</label>
        <input type="number" id="friction" value="0.0001"/>
      </div>
    </div>
  </div>
  <div class="row">
    <button id="hide_btn">Hide Controls</button>
    <button id="reset_btn">Clear Drawing</button>
    <button id="stop_btn">Stop Drawing</button>
  </div>
</form>
<div class="container">
  <canvas></canvas>
  <svg id="controls" width="800" height="800" viewBox="0 0 800 800">
    <circle class="draggable" id="pivot1" cx="80" cy="100" r="20" stroke="#ff0000" fill="rgba(255,255,255,0)"/>
    <circle class="draggable" id="pivot2" cx="720" cy="100" r="20" stroke="#0000ff" fill="rgba(255,255,255,0)"/>
    <circle class="draggable" id="drawing_center" cx="400" cy="480" r="10" stroke="#fff" fill="rgba(255,255,255,0)"/>
    <line x1="80" y1="100" x2="400" y2="480" stroke="#ff0000" />
    <line x1="720" y1="100" x2="400" y2="480" stroke="#0000ff" />
    <circle id="pendulum1" cx="80" cy="100" r="5" fill="#ff0000"/>
    <circle id="pendulum2" cx="720" cy="100" r="5" fill="#0000ff"/>
  </svg>
</div>

              
            
!

CSS

              
                body {
  background-color: #000;
}

p {
  color: white;
  font-size: 20px;
}

.container {
  position: relative;
  margin: 0 auto;
  width: 800px;
  height: 800px;
}

canvas {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border: 2px solid rgba(255,255,255,0.1)
}

svg {
  position: absolute;
  left: 0;
  top: 0;
}

.draggable {
  cursor: pointer;
}

form {
  width: 800px;
  color: #fff;
  font-family: monospace;
  margin: 0 auto;
}

.row {
  display: flex;
}

.column {
  width: 50%;
  padding: 0 8px;
}

.input-holder {
  margin-bottom: 10px;
}

label {
  display: block;
  font-size: 1.1em;
}

input {
  display: block;
  width: 100%;
}

button {
  cursor: pointer;
  margin: 8px;
  flex-grow: 1;
  font-family: monospace;
  font-size: 1.4em;
  padding: 6px;
  background-color: #fff;
  border: 0;
}
              
            
!

JS

              
                class Controls {
  constructor(harmonograph) {
    this.controls = document.getElementById('controls');
    this.pivots = [document.getElementById('pivot1'), document.getElementById('pivot2')];
    this.drawingCenter = document.getElementById('drawing_center');
    this.minY = 20;
    this.maxY = 580;
    this.x;
    this.y;
    this.startTime;

    this.updateHarmonograph = harmonograph.updatePositioning;
    const { pivot1, pivot2, center } = this.centerPoints;
    harmonograph.setPendulums(pivot1, pivot2, center, document.querySelectorAll('.period'), document.querySelectorAll('.amplitude'), document.querySelector('#friction'), document.querySelector('#offset'));
    this.updateHarmonograph(this.centerPoints);

    this.centerMouseMoveHandler = this.centerMouseMoveHandler.bind(this);
    this.startTimer = this.startTimer.bind(this);

    this.mouseMoveHandlers = [0, 1].map(i => this.createMouseMoveHandler(i)).concat([this.centerMouseMoveHandler]);
    this.mouseDownHandlers = [0, 1, 2].map(i => this.createMouseDownHandler(i));
    this.pivots.forEach((p, i) => p.addEventListener('mousedown', this.mouseDownHandlers[i]));
    this.drawingCenter.addEventListener('mousedown', this.mouseDownHandlers[2]);
  }

  createMouseDownHandler(i) {
    return e => {
      this.x = e.x;
      this.y = e.y;
      document.addEventListener('mousemove', this.mouseMoveHandlers[i]);
      document.addEventListener('mouseup', (e) => document.removeEventListener('mousemove', this.mouseMoveHandlers[i]));
    }
  }

  createMouseMoveHandler(i) {
    return e => {
      const deltaY = e.y - this.y;
      const deltaX = e.x - this.x;

      this.pivots.forEach((p, j) => {
        const minX = j ? 400 : 20;
        const maxX = j ? 780 : 400;
        const currY = parseInt(p.getAttribute('cy'));
        const currX = parseInt(p.getAttribute('cx'));
        const nextY = currY + deltaY > this.maxY ? this.maxY : currY + deltaY < this.minY ? this.minY : currY + deltaY;

        p.setAttribute('cy', nextY);

        if (i && j || !i && !j) {
          p.setAttribute('cx', currX + deltaX > this.maxX ? this.maxX : currX + deltaX < this.minX ? this.minX : currX + deltaX);
        } else {
          p.setAttribute('cx', currX - deltaX > this.maxX ? this.maxX : currX - deltaX < this.minX ? this.minX : currX - deltaX);
        }
      });

      this.y = e.y;
      this.x = e.x;
      this.updateHarmonograph(this.centerPoints);
    };
  }

  centerMouseMoveHandler(e) {
    const deltaY = e.y - this.y;
    const currY = parseInt(this.drawingCenter.getAttribute('cy'));
    const nextY = currY + deltaY > this.maxY ? this.maxY : currY + deltaY < this.minY ? this.minY : currY + deltaY;
    this.drawingCenter.setAttribute('cy', nextY);
    this.y = e.y;
    this.updateHarmonograph(this.centerPoints);
  }

  startTimer() {
    this.startTime = Date.now();
  }

  get centerPoints() {
    return {
      pivot1: { x: parseInt(this.pivots[0].getAttribute('cx')), y: parseInt(this.pivots[0].getAttribute('cy')) },
      pivot2: { x: parseInt(this.pivots[1].getAttribute('cx')), y: parseInt(this.pivots[1].getAttribute('cy')) },
      center: { x: parseInt(this.drawingCenter.getAttribute('cx')), y: parseInt(this.drawingCenter.getAttribute('cy')) },
    }
  }

  get currentTime() {
    return Date.now() - this.startTime;
  }
}

class Harmonograph {
  constructor(arms) {
    this.armLeft = arms[0];
    this.armRight = arms[1];
    this.armLength;
    this.pendulumLeft;
    this.pendulumRight;
    this.x;
    this.y;

    this.updatePositioning = this.updatePositioning.bind(this);
  }

  reset() {
    [this.pendulumLeft, this.pendulumRight].forEach(p => p.resetAmplitude());
  }

  updatePositioning({ pivot1, pivot2, center }) {
    const angle = this.findAngle(pivot1, center);
    this.armLength = Math.sqrt(Math.pow(center.x - pivot1.x, 2) + Math.pow(center.y - pivot1.y, 2));
    this.pendulumLeft.updatePosition(pivot1.x, pivot1.y, angle);
    this.pendulumRight.updatePosition(pivot2.x, pivot2.y, angle);
  }

  setArms({ x: leftX, y: leftY }, { x: rightX, y: rightY }) {
    this.armLeft.setAttribute('x1', leftX);
    this.armLeft.setAttribute('y1', leftY);
    this.armLeft.setAttribute('x2', this.xy.x);
    this.armLeft.setAttribute('y2', this.xy.y);
    this.armRight.setAttribute('x1', rightX);
    this.armRight.setAttribute('y1', rightY);
    this.armRight.setAttribute('x2', this.xy.x);
    this.armRight.setAttribute('y2', this.xy.y);
  }

  findAngle(pivot1, center) {
    const x = Math.abs(pivot1.x - center.x);
    const y = Math.abs(pivot1.y - center.y);
    const arm = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
    return Math.acos((Math.pow(y, 2) + Math.pow(arm, 2) - Math.pow(x, 2)) / (2 * y * arm));
  }

  findCenter(leftCoords, rightCoords) {
    const maxX = Math.max(rightCoords.x, leftCoords.x);
    const minX = Math.min(rightCoords.x, leftCoords.x);
    const maxY = Math.max(rightCoords.y, leftCoords.y);
    const minY = Math.min(rightCoords.y, leftCoords.y);
    const shortLength = Math.sqrt(Math.pow(maxX - minX, 2) + Math.pow(maxY - minY, 2)) / 2;
    const midPoint = { x: ((maxX - minX) / 2) + minX, y: ((maxY - minY) / 2) + minY };
    const longLength = Math.sqrt(Math.pow(this.armLength, 2) - Math.pow(shortLength, 2));

    // slope perpendicular to line from left pendulum to right pendulum
    let m = -1 * (midPoint.x - leftCoords.x) / (midPoint.y - leftCoords.y);

    if (m > 0) {
      this.x = (longLength * Math.cos(Math.atan(m))) + midPoint.x;
      this.y = (longLength * Math.sin(Math.atan(m))) + midPoint.y;
    } else {
      this.x = midPoint.x - (longLength * Math.cos(Math.atan(m)));
      this.y = midPoint.y - (longLength * Math.sin(Math.atan(m)));
    }
  }

  setPendulums(pivot1, pivot2, center, periodInputs, amplitudeInputs, frictionInput, offsetInput) {
    const angle = this.findAngle(pivot1, center);
    this.pendulumLeft = new Pendulum(pivot1.x, pivot1.y, angle, periodInputs[0], amplitudeInputs[0], frictionInput, offsetInput, 0, document.getElementById('pendulum1'));
    this.pendulumRight = new Pendulum(pivot2.x, pivot2.y, angle, periodInputs[1], amplitudeInputs[1], frictionInput, offsetInput, 1, document.getElementById('pendulum2'));
  }

  advance(time) {
    [this.pendulumLeft, this.pendulumRight].forEach(p => p.swing(time));
    this.findCenter(this.pendulumLeft.coords, this.pendulumRight.coords);
    this.setArms(this.pendulumLeft.coords, this.pendulumRight.coords);
  }

  get xy() {
    return { x: this.x, y: this.y };
  }
}

class Pendulum {
  constructor(x, y, angle, periodInput, amplitudeInput, frictionInput, offsetInput, side, ref) {
    this.x;
    this.y;
    this.angle = angle;
    this.side = side;
    this.ref = ref;
    this.centerX = parseInt(x);
    this.centerY = parseInt(y);
    this.period = parseFloat(periodInput.value);
    this.friction = parseFloat(frictionInput.value);
    this.amplitude = parseFloat(amplitudeInput.value);
    this.offset = parseFloat(offsetInput.value);
    this.currentAmplitude = this.amplitude;

    this.updatePeriod = this.updatePeriod.bind(this);
    this.updateAmplitude = this.updateAmplitude.bind(this);
    this.updateFriction = this.updateFriction.bind(this);
    this.updateOffset = this.updateOffset.bind(this);
    this.resetAmplitude = this.resetAmplitude(amplitudeInput);

    periodInput.addEventListener('change', this.updatePeriod);
    amplitudeInput.addEventListener('change', this.updateAmplitude);
    frictionInput.addEventListener('change', this.updateFriction);
    offsetInput.addEventListener('change', this.updateOffset);
  }

  updatePeriod(e) {
    this.period = parseFloat(e.target.value);
  }

  updateAmplitude(e) {
    const newAmplitude = parseFloat(e.target.value);
    this.currentAmplitude = (this.currentAmplitude / this.amplitude) * newAmplitude;
    this.amplitude = newAmplitude;
  }

  resetAmplitude(ref) {
    return () => {
      this.currentAmplitude = parseFloat(ref.value);
    }
  }

  updateFriction(e) {
    this.friction = parseFloat(e.target.value);
  }

  updateOffset(e) {
    this.offset = parseFloat(e.target.value);
  }

  getCurrentCoords(time) {
    const adjustedTime = time / 2000;
    const adjustedPeriod = this.side ? this.period + (this.period * this.offset) : this.period;
    this.currentAmplitude = ((1 - this.friction) * this.currentAmplitude);

    // the sine fn will just give a y value
    const hypotenuse = this.currentAmplitude * Math.sin(adjustedTime * adjustedPeriod);
    const deltaX = (Math.abs(hypotenuse) / Math.sin(90)) * Math.sin(this.angle);
    const deltaY = Math.sqrt(Math.pow(hypotenuse, 2) - Math.pow(deltaX, 2));

    if (this.side && hypotenuse > 0) {
      return { x: this.centerX + deltaX, y: this.centerY - deltaY };
    } else if (this.side && hypotenuse <= 0) {
      return { x: this.centerX - deltaX, y: this.centerY + deltaY };
    } else if (!this.side && hypotenuse > 0) {
      return { x: this.centerX + deltaX, y: this.centerY + deltaY };
    } else {
      return { x: this.centerX - deltaX, y: this.centerY - deltaY };
    }
  }

  updatePosition(x, y, angle) {
    this.centerX = x;
    this.centerY = y;
    this.angle = angle;
  }

  swing(time) {
    const { x, y } = this.getCurrentCoords(time);
    this.x = x;
    this.y = y;
    this.ref.setAttribute('cx', x);
    this.ref.setAttribute('cy', y);
  }

  get coords() {
    return { x: this.x, y: this.y };
  }
}

(function() {
  const svg = document.querySelector('svg');
  const arms = Array.from(document.getElementsByTagName('line'));
  const canvas = document.getElementsByTagName('canvas')[0];
  const hideBtn = document.getElementById('hide_btn');
  const stopBtn = document.getElementById('stop_btn');
  canvas.width = 1600;
  canvas.height = 1600;
  const ctx = canvas.getContext('2d');
  const harmonograph = new Harmonograph(arms, canvas);
  const controls = new Controls(harmonograph);
  let isHidden = false;
  let isStopped = false;
  let drawRef;

  init();

  function addListeners() {
    document.getElementById('reset_btn').addEventListener('click', e => {
      e.preventDefault();
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    });

    hideBtn.addEventListener('click', toggleHideStatus);
    stopBtn.addEventListener('click', toggleStoppedStatus);
  }

  function toggleHideStatus(e) {
    e.preventDefault();
    if (isHidden) {
      svg.style.display = 'block';
      hideBtn.innerText = 'Hide Controls';
    } else {
      svg.style.display = 'none';
      hideBtn.innerText = 'Show Controls';
    }
    isHidden = !isHidden;
  }

  function toggleStoppedStatus(e) {
    e.preventDefault();
    if (isStopped) {
      startGraph();
      stopBtn.innerText = 'Stop Drawing';
    } else {
      cancelAnimationFrame(drawRef);
      stopBtn.innerText = 'Start New Drawing';
    }
    isStopped = !isStopped;
  }

  function startGraph() {
    controls.startTimer();
    harmonograph.reset();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    requestAnimationFrame(draw);
  }

  function draw() {
    harmonograph.advance(controls.currentTime + 1);
    drawPoint(harmonograph.xy);
    drawRef = requestAnimationFrame(draw);
  }

  function drawPoint(pt) {
    ctx.fillStyle = 'rgba(255,0,255,0.6)';
    ctx.beginPath();
    ctx.arc(pt.x * 2, pt.y * 2, 1, 0, Math.PI * 2, false);
    ctx.fill();
    ctx.closePath();
  }

  function init() {
    addListeners();
    startGraph();
  }
})();
              
            
!
999px

Console