Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <p>Click canvas to add points to line. Connect points to end polygon. Click 'Snapshot' to store frame. Move points and snapshot again to build up frames. Click 'Morph' to play the frames. Click 'Reset' to erase frames.</p> 
<p>
  Line tension <input type="range" min="0" max="1" value="0.4" step="0.1" class="slider" id="lineTension"> <span id='lineTensionDisplay'></span>

</p>
<p>
  <button id='snapshot'>Snapshot</button>
  <button id='morph'>Morph</button>
  <button id='reset'>Reset</button>
   <input type="range" min="20" max="2000" value="400" class="slider" id="morphSpeed"> <span id='morphSpeedDisplay'></span>
</p> 

<div id="container"></div>
              
            
!

CSS

              
                body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f0f0f0;
}
#container {
  width: 800px;
  height: 400px;
  margin: 10px;
}
p {
  margin: 4px;
}
.slider {
  margin-top: 5px;
}
 
              
            
!

JS

              
                const width = 1200,
  height = 800,
  hitRadius = 20, // radius of the rect used to show snap-proximity to points
  // Make a stage, layer
  stage = new Konva.Stage({
    container: "container",
    width: width,
    height: height,
    x: 0,
    y: 0,
    draggable: false
  }),
  layer = new Konva.Layer({ draggable: false }),
  // This circle is used to show when the dragging point can be dropped on another
  proximityCircle = new Konva.Circle({
    x: 0,
    y: 0,
    stroke: "magenta",
    strokeWidth: 2,
    radius: hitRadius,
    visible: false
  });

stage.add(layer);
layer.add(proximityCircle);

let lines = [],
  runTimeMs = 200,
  lineTension = 0.5,
  lineCounter = 0,
  pointCounter = 0,
  drawMode = "adding",
  currentLine,
  currentPoint;

// When we see mouseup on the stage what we do depends on the state:
// - if drawing, fix the clicked position as a new point
// - if adding, which means no points are yet drawn, make a new line at this position and set the first point.
stage.on("mouseup", function (evt) { 

  if (drawMode === "drawing") {
    fixPoint();
  }
  if (drawMode === "adding") {
    startLine();
    drawMode === "drawing";
  }
  if (drawMode === "editing" && currentLine) {
    const pos = currentLine.line.getRelativePointerPosition();
    currentPoint.moveTo(pos);
    currentLine.redraw();
  }
});

stage.on("mousedown", function (evt) {
  if (drawMode === "editing" && evt.target.hasName("editCircle")) {
    currentPoint = evt.target.getAttr("parentPoint");
    currentLine = currentPoint.line;
  }
});

// If the user is relocating a point then update and redraw the line.
stage.on("mousemove", function (evt) {
  if (drawMode === "drawing" && currentPoint) {
    const pos = currentLine.line.getRelativePointerPosition();
    currentPoint.moveTo(pos);
    currentLine.redraw();
  }
});

// If the user is relocating a point then update and redraw the line.
stage.on("dragmove", function (evt) { 
  if (currentPoint) { 
    const pos = currentLine.line.getRelativePointerPosition();
    currentPoint.moveTo(pos);
    currentLine.redraw();
  }
});

// Called when the user places the first point of a line
function startLine(evt) {
  const pos = stage.getPointerPosition();

  currentLine = new connectedLine(layer, pos);

  // now use position relative to line origin to set the points.
  const relPos = currentLine.line.getRelativePointerPosition();

  // Point #1 is the first point of the line
  currentPoint = currentLine.addPoint(relPos);
  currentPoint.moveTo(relPos);

  // Point #2 is the second point of the line. This point will follow the mouse
  // position until the user clicks the stage.
  currentPoint = currentLine.addPoint(relPos);
  currentPoint.moveTo(relPos);
  drawMode = "drawing";
}

// Called when the user clicks that stage for points #2 onwards.
// If the click is within the proximity of another point then
// we close the line and set the anchors to listening and draggable.
function fixPoint(evt) { 
  if (currentPoint) {
    const pos = currentLine.line.getRelativePointerPosition();

    const isHit = currentPoint.moveTo(pos);

    if (isHit) {
      proximityCircle.visible(false);

      // remove the current point !
      currentPoint.destroy();
      currentLine.eraseLast();

      currentLine.line.closed(true);
      currentLine.redraw();

      currentLine = undefined;
      currentPoint = undefined;

      const editCircles = layer.find(".editCircle");
      for (const c of editCircles) {
        c.listening(true);
        c.draggable(true);
        c.stroke("cyan");
      }

      drawMode = "editing";
    } else {
      currentPoint = currentLine.addPoint(pos);
      currentLine.redraw();
    }
  }
}

// ok - this is to do with animation. We draw the shape we want, then use Snapshot to store the points
// for the line we see. Then we move one or more points and click Snapshot again to store a second set of points.
// Now click Morph and the line will morph between the sets of points. You can have as many snapshots as ou like!
$("#snapshot").on("click", function () {
  let lineCnt = 0;
  for (const line of lines) {
    lineCnt++;
    const frame = [];
    for (const point of line.points) {
      frame.push({ x: point.x, y: point.y });
    }
    line.frames.push(frame);
  } 
});

// More animation stuff.  Hide the anchors circles,  start the animation.
let fromFrameIdx = 0,
  anim = undefined;
$("#morph").on("click", function () {

  const editCircles = layer.find(".editCircle");
  for (const c of editCircles) {
    c.visible(false);
  }

  // how many frames to process.
  const framesToRun = lines[0].frames.length; 
  if (framesToRun < 2) { 
    return false;
  }
  fromFrameIdx = 0;

  runLimit = runTimeMs;
  anim = makeAnimation();
  anim.start();
});

// Reset button handler - stop the animation, show the anchor points, draw the line
// using the first set of saved points and clear the snaphots.
$("#reset").on("click", function () {
  if (anim) {
    anim.stop();
  }

  const editCircles = layer.find(".editCircle");
  for (const c of editCircles) {
    c.visible(true);
  }

  for (const line of lines) {
    if (line.frames.length > 0) {
      for (let i = 0; i < line.frames[0].length; i++) {
        const resetPos = line.frames[0][i];
        line.points[i].moveTo(resetPos);
      }

      line.redraw();
      line.frames = [];
    }
  }
});

//
// Finally construction of the animation function
let direction = 1,
  runLimit = 0,
  lastFlippedTime = 0;
function makeAnimation() {
  // frame.time property which is the number of milliseconds that the animation has been running
  const safety = 20000;
  let cnt = 0;
 
  
  const anim = new Konva.Animation(function (frame) {
    const time = frame.time,
      timeDiff = frame.timeDiff,
      frameRate = frame.frameRate;

    try {
      // divide by time we want the animation to run
      const distFraction = (frame.time - lastFlippedTime) / runTimeMs;

      // let fromFrameIdx = 0,
      //   direction = 1;
      for (const line of lines) {
        const fromSnapshot = line.frames[fromFrameIdx];
        const toSnapshot = line.frames[fromFrameIdx + direction];

        // move each point from its current position toward its final position
        linePointsNow = [];
        for (let i = 0; i < fromSnapshot.length; i++) {
          const fromPt = fromSnapshot[i],
            toPt = toSnapshot[i];

          const fullDist = { x: toPt.x - fromPt.x, y: toPt.y - fromPt.y };

          linePointsNow.push(
            fromPt.x + fullDist.x * distFraction,
            fromPt.y + fullDist.y * distFraction
          );
        }

        line.line.points(linePointsNow);
      }

      if (cnt++ > safety || frame.time > runLimit) {
        runLimit = runLimit + runTimeMs;
        lastFlippedTime = frame.time;
        fromFrameIdx = fromFrameIdx + direction;
        console.log(
          "Anim stop, cnt = " +
            cnt +
            " time " +
            frame.time +
            " vs limit " +
            runTimeMs +
            " fromFrameIdx = " +
            fromFrameIdx +
            " of " +
            lines[0].frames.length
        );


        
        if (direction === 1 && fromFrameIdx === lines[0].frames.length - 1) {
          console.log("Hit upper limt, flip to dir = -1");
          direction = -1;
          fromFrameIdx = lines[0].frames.length - 1;
        } else if (direction === -1 && fromFrameIdx === 0) {
          // reverse direction
          console.log("Hit lower limt, flip to dir = 1");
          direction = 1;
          fromFrameIdx = 0;
          // anim.stop();
        }
        console.log(
          "Dir now " +
            direction +
            " range 0 to " +
            (lines[0].frames.length - 1) +
            " current idx val " +
            fromFrameIdx
        );
      }
    } catch (err) {
      console.log("err", err);
    }
  }, layer);

  return anim;
}

// changes the morph speed.
$("#morphSpeed").on("input", function () {
  runTimeMs = parseInt($(this).val()); 
  showMorphSpeedDisplay(runTimeMs);
});

function showMorphSpeedDisplay(speed) {
  $("#morphSpeedDisplay").html(speed + "ms");
}
showMorphSpeedDisplay(runTimeMs);

// changes the line tension.
$("#lineTension").on("input", function () {
  lineTension = parseFloat($(this).val()); 
  showLineTensionDisplay(lineTension);
});
function showLineTensionDisplay(tension) {
  $("#lineTensionDisplay").html(tension);
  redraw();
}
showLineTensionDisplay(lineTension);

function redraw() {
  for (const line of lines) {
    line.line.tension(lineTension);
    line.redraw();
  }
}

/*
 * The augmented line class.
 */
class connectedLine {
  constructor(layer, pos) {
    this.id = "line" + lineCounter++;

    // this is the Konva.Line to be used for drawing the outline of the shape
    this.line = new Konva.Line({
      id: this.id,
      position: pos,
      stroke: "red",
      strokeWidth: 3,
      fill: "lime",
      hitStrokeWidth: 10,
      points: [pos.x, pos.y, pos.x, pos.y],
      draggable: true,
      tension: lineTension
    });
    this.line.setAttr("savedTension", lineTension);

    // will be used to hold multiple versions of the points to support animation later
    this.frames = [];

    // Handle dragging of the line as a whole - not individual points.
    let dragPos;
    this.line.on("dragstart", function (evt) {
      dragPos = this.position();
    });

    // when the line is dragged we have to move the anchors to match this movement.
    const that = this;
    this.line.on("dragmove", function (evt) {
      const pos = this.position();
      const diff = { x: pos.x - dragPos.x, y: pos.y - dragPos.y };
      dragPos = this.position();
      const circles = layer.find("." + this.id());
      for (const c of circles) {
        c.position({ x: c.position().x + diff.x, y: c.position().y + diff.y });
      }
      that.redraw();
    });

    layer.add(this.line);
    lines.push(this);
    this.redraw();
  }

  // a store for the list of points in the line. We need this because we will edit the points.
  points = [];

  // add a point to the line.
  addPoint = function (pos) {
    //    const linePos = this.line.position();

    const pt = new Point(pointCounter++, this, pos);
    this.points.push(pt);

    if (!this.firstPoint) {
      this.firstPoint = pt;
    }
    this.lastPoint = pt;

    return pt;
  };

  eraseLast = function () {
    this.points.pop();
  };

  redraw = function () {
    let pts = [];
    for (let point of this.points) {
      pts.push(point.x, point.y);
    }
    this.line.points(pts);
  };
}

class Point {
  constructor(pointCounter, line, pos) {
    this.id = "pt" + pointCounter;
    this.ptNo = pointCounter;
    this.x = pos.x;
    this.y = pos.y;
    this.line = line;

    this.editCircle = new Konva.Circle({
      x: this.x,
      y: this.y,
      fill: "blue",
      radius: 10,
      strokewWidth: 3,
      name: "editCircle " + line.id + " editCircle"
    });
    this.editCircle.setAttr("point", this);
    this.editCircle.setAttr("parentPoint", this);
    layer.add(this.editCircle);
  }

  moveTo = function (pos) { 
    let isHit = false;
    this.x = pos.x;
    this.y = pos.y;
    proximityCircle.visible(false);
    if (drawMode === "drawing") {
      for (let point of this.line.points) {
        if (point.id !== this.id && point.ptNo !== this.ptNo - 1) {
          const dist = this.getDistance(pos.x, pos.y, point.x, point.y);

          if (dist < hitRadius) {
            // hitRadius is an arbitrary distance, set in constants at top of page.

            const linePos = this.line.line.position(),
              circlePos = { x: pos.x + linePos.x, y: pos.y + linePos.y };
            proximityCircle.position(circlePos);
            proximityCircle.visible(true);
            isHit = true;
            pos.x = point.x;
            pos.y = point.y;
            break;
          }
        }
      }
    }

    this.x = pos.x;
    this.y = pos.y;
    this.editCircle.position({
      x: this.line.line.position().x + pos.x,
      y: this.line.line.position().y + pos.y
    });

    return isHit;
  };

  // Compute the distance between 2 points.
  getDistance = function (x1, y1, x2, y2) {
    let y = x2 - x1;
    let x = y2 - y1;

    return Math.sqrt(x * x + y * y);
  };

  destroy() {
    this.editCircle.destroy();
  }
}

              
            
!
999px

Console