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

              
                <canvas style="position: relative; cursor: none;" id= "canvas_manual_drawing_demo" width="750" height="800">
        </canvas>
              
            
!

CSS

              
                
              
            
!

JS

              
                
// hanging something
var settings = {
    segmentLength: 10,
    gravity: {x: 0, y: 2},
    paintDots: true,
    dotCount: 15
}

// Replace above settings with below for a snake-like expression
// var settings = {
//     segmentLength: 1,
//     gravity: {x: 0, y: 0},
//     paintDots: true,
//     dotCount: 100
// }

var HEIGHT = 750;
var WIDTH = 800;

var ensureValidNumber = function(n, obj){
    if(n === undefined)
        {
            console.error(obj);
            throw "Undefined";
        }
    if(isNaN(n))
    {
        console.error(obj);
        throw "Nan";
    }
    if(!isFinite(n)){
        console.error(obj);
        throw "Infinity";
    }
}

var ensureVector = function(v){
    var throwAlert = function(msg, obj){
        console.error(msg, v);
        throw msg;
    }
    if(!v)
    {
        throwAlert("Falsy vector!", v);
    }
    ensureValidNumber(v.x, v);
    ensureValidNumber(v.y, v);
}


var createDot = function(x, y){
    ensureValidNumber(x);
    ensureValidNumber(y);
  var result =  {loc: {x:x, y:y}, vel: {x: 0, y:0}};
  ensureVector(result.loc);
  ensureVector(result.vel);
  return result;
}


var mainDot = createDot(WIDTH/2, HEIGHT/2-settings.segmentLength);
var dots = [];

var resizeDotCount = function(dotCount){
    dots = [];
    // Grow if more
    for(var i = 0; i < dotCount; i++){
        dots.push(createDot(WIDTH/2, HEIGHT/2+i*settings.segmentLength));
        ensureVector(dots[i].loc);
        ensureVector(dots[i].vel);
    }
}

resizeDotCount(settings.dotCount);


var addVector = function(existing, add){
    return {x:existing.x + add.x, y: existing.y + add.y};
}

var getDistance = function(loc1, loc2){
    ensureVector(loc1);
    ensureVector(loc2);
    
    var xDist = loc1.x-loc2.x;
    ensureValidNumber(xDist);

    var yDist = loc1.y-loc2.y;
    ensureValidNumber(yDist);

  var v = xDist*xDist + yDist * yDist;
  ensureValidNumber(v, {debud1: loc1, debug2: loc2});
  var result = Math.sqrt(v);
  ensureValidNumber(result, v);
  
    return result;
}

var getVectorLength = function(vector){
    ensureVector(vector);
    var existinglength = getDistance({x:0,y:0}, vector);
    ensureValidNumber(existinglength);
    return existinglength;
}

var setVectorLength = function(vector, length){
    if(length == 0)
        return {x:0, y:0};
        ensureValidNumber(length, length);
    ensureVector(vector);
    var existinglength = getVectorLength(vector);
    ensureValidNumber(existinglength);
    if(existinglength == 0)
        return {x:0, y:0};
    
        
    var newX = vector.x / existinglength * length;
    ensureValidNumber(newX);

    var newY = vector.y / existinglength * length;
    ensureValidNumber(newY);

    var newVector = {x: newX, y: newY};
    ensureVector(newVector);
    return newVector;
}

var getDistanceVector = function(loc1, loc2){
  var distance = {x: loc2.x - loc1.x, y:loc2.y - loc1.y};
  ensureVector(distance);
  return distance;
}

var adjustVectorLength = function(vector, factor){
    ensureVector(vector);
    ensureValidNumber(factor);

    var length = getVectorLength(vector);
    
    ensureValidNumber(length);

    var newLength = length * factor;
    ensureValidNumber(newLength);

    var newVector = setVectorLength(vector, newLength);
    ensureVector(newVector);

    return newVector;
}

// Logic
var updateLogic = function(){
  var previousDot = mainDot;
  for(var i = 0; i < dots.length; i++){
    var dot = dots[i];
    
    // Validation
    ensureVector(previousDot.loc);
    ensureVector(dot.loc);

    // Apply dot's own velocity to dot
    dot.loc = addVector(dot.loc, dot.vel);

    // Get vector from this position to previous nodes position
    var directionVector = {x: dot.loc.x - previousDot.loc.x, y: dot.loc.y - previousDot.loc.y};
    var directionVector = setVectorLength(directionVector, settings.segmentLength);

    // Calculate the position where the dot should be moved to
    var desiredNewPosition = {x:previousDot.loc.x + directionVector.x, y: previousDot.loc.y + directionVector.y};

    // Calculate the velocity to apply to the dot based on the instant movement to a new position
    var positionMoveVelocity = {x: desiredNewPosition.x - dot.loc.x, y: desiredNewPosition.y - dot.loc.y};

    // Slow down the position move velocity to make the tail relax faster
    positionMoveVelocity = adjustVectorLength(positionMoveVelocity, 0.5); // The closer to one, the longer time willt he tail vibrate

    // Apply position move velocity
    dot.vel = addVector(dot.vel, positionMoveVelocity);

    // Add settings.gravity
    dot.vel = addVector(dot.vel, settings.gravity);

    // Brake velocity for a slow movement
    dot.vel = adjustVectorLength(dot.vel, 0.8); // The closer to 1, the faster does the tail move
    
    // The difference from current position to desired position is added to the velocity as a force
    dot.loc = desiredNewPosition;

    // Move to next dot in line
    previousDot = dot;
  }
}


// Drawing
var canvas = document.getElementById("canvas_manual_drawing_demo");
var ctx = canvas.getContext("2d");

// Controls
var active = false;
canvas.addEventListener("mouseenter", function (e) {
    active = true;
});
canvas.addEventListener("mouseleave", function (e) {
    active = false;
});
canvas.addEventListener("mousemove", function (e) {
    mainDot.loc.x = e.layerX;
    mainDot.loc.y = e.layerY;
});

var repaint = function(){
  // Clear
  ctx.fillStyle = "#999";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // Draw line
  ctx.strokeStyle = "rgb(144,80,80)";
  ctx.beginPath();

  ctx.moveTo(mainDot.loc.x, mainDot.loc.y);

  // Draw line
  for(var i = 0; i < dots.length; i++){
    var dot = dots[i];
    ctx.lineTo(dot.loc.x, dot.loc.y);
    ctx.stroke();
  }

  // Draw dots
  if(settings.paintDots){
    ctx.fillStyle = "#F00";
    var dotWidth = 4;
    for(var i = 0; i < dots.length; i++){
      var dot = dots[i];
      ctx.fillRect(dot.loc.x-dotWidth/2, dot.loc.y-dotWidth/2, dotWidth, dotWidth);
    }
  }
}

var paintPauseText = function(){
  ctx.strokeStyle = "#000";
  ctx.font = "20px Arial";
  ctx.fillText("(Paused to save resources - hover to activate)", 150, 50);
}

repaint();
var pausePainted = false; // This is used to only draw text once whan paused to save resources
var tick = function(){
  if(active){ 
    updateLogic();
    repaint();
    pausePainted = false;
  }else{
    if(!pausePainted){
      paintPauseText();
      pausePainted = true;
    }
  }
  setTimeout(tick, 25);
  
}
tick();
              
            
!
999px

Console