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

              
                <canvas id="c"></canvas>
              
            
!

CSS

              
                body, html {
  margin: 0;
  padding: 0;
  
  canvas {
    display: block;
  }
}
              
            
!

JS

              
                // Just an interface for renderables
interface IRenderable {
  Step(): void;
  Draw(ctx: CanvasRenderingContext2D): void;
}

// Strategy pattern
interface IMoveBehaviour {
  Move(): void;
}

// A 2D vector
class Vector2D {
  constructor(public x: number, public y: number){}
}

// A rectangle
class Rect {
  constructor(public x: number, public y: number, public w: number, public h: number){}
}

/**
  A concrete strategy, this one lets a Rect move diagonally. All it 
  needs is a rect, velocity and bounding box. It does not know what 
  it is moving.
*/
class DiagonalMove implements IMoveBehaviour {
  private rect: Rect;
  private velocity: Vector2D;
  private boundingBox: Rect;
  
  // We need some information, some implementations might not need this stuff
  constructor(rect: Rect, vel: Vector2D, boundingBox: Rect) {
    this.rect = rect;
    this.velocity = vel;
    this.boundingBox = boundingBox;
  }
  
  // The exposed strategy / behaviour
  Move(): void {
    this.rect.x += this.velocity.x;
    if(this.rect.x >= this.boundingBox.w - this.rect.w) {
      this.rect.x = this.boundingBox.w - this.rect.w;
      this.velocity.x *= -1;
    } else if (this.rect.x <= 0) {
      this.rect.x = 0;
      this.velocity.x *= -1;
    }
    
    this.rect.y += this.velocity.y;
    if(this.rect.y >= this.boundingBox.h - this.rect.h) {
      this.rect.y = this.boundingBox.h - this.rect.h;
      this.velocity.y *= -1;
    } else if (this.rect.y <= 0) {
      this.rect.y = 0;
      this.velocity.y *= -1;
    }
  }
}

/**
  A concrete strategy, this one lets a Rect move circularly. All it 
  needs is a rect, center point and radius. It does not know what 
  it is moving.
*/
class CircularMove implements IMoveBehaviour {
  private rect: Rect;
  private center: Rect;
  private radius: number;
  private angle: number;
  
  constructor(rect: Rect, center: Rect, radius: number) {
    this.rect = rect;
    this.center = center;
    this.radius = radius;
    this.angle = 0;
  }
  
  private rad(deg: number): number {
    return (deg * (Math.PI / 180));
  }
  
  // The exposed strategy / behaviour
  Move(): void {
    this.rect.x = (this.center.x + (this.radius * Math.cos(this.rad(this.angle))));
    this.rect.y = (this.center.y + (this.radius * Math.sin(this.rad(this.angle))));
    this.angle  = ((this.angle + 2) % 360);
  }
}

// The renderable subject
class MySubject implements IRenderable {
  r: Rect;            // position and size
  
  // The move behaviour, the strategy pattern in effect. This 
  // class does not know what move behaviours exist, nor will
  // this class ever know which one it will get, it just knows
  // it contains a Move() method as described in the interface.
  b: IMoveBehaviour;
  
  // constructor sets properties
  constructor(r, b) {
    this.r = r;
    this.b = b; // set the strategy
  }
  
  // Step the position and bounce off the edges
  Step(): void {
    this.b.Move(); // invoke our strategy provider
  }
  
  // Draw the box
  Draw(ctx: CanvasRenderingContext2D): void {
    ctx.fillStyle = '#cecece';
    ctx.fillRect(this.r.x, this.r.y, this.r.w, this.r.h);
  }
}

// Singleton pattern
class RenderSystem {
  // Singleton instance reference
  static private _instance;
  
  // Some private properties
  private context;
  private canvas;
  private looping;
  private renderables: Array<IRenderable> = [];

  // A singleton should have a private constructor
  private constructor() {
    this.canvas   = document.getElementById('c');
    this.context  = this.canvas.getContext('2d');
  }

  // A singleton should have static access to the static single 
  // instance reference, and create one when needed
  static GetInstance(): RenderSystem {
    if(!this._instance) {
      this._instance = new RenderSystem();
    }
    
    return this._instance;
  }

  // Add a renderable to the list
  AddRenderable(r: IRenderable): void {
    this.renderables.push(r);
  }

  // Step all renderables
  Step(): void {
    for(var i in this.renderables) {
      this.renderables[i].Step();
    }
  }

  // Draw all renderables after clearing the screen
  Draw(): void {
    this.context.fillStyle = 'rgba(0, 0, 0, 0.05)';
    this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i in this.renderables) {
      this.renderables[i].Draw(this.context);
    }
  }
  
  // The render loop
  Loop(): void {
    if(this.looping) {
      return;
    }
    
    this.looping = true;
    
    var that = this;
    +(function step() {
      requestAnimationFrame(step);
      
      that.Step();
      that.Draw();
      
    })();
  }
}


window.addEventListener('load', function() {
  var canvas  = document.getElementById('c'),
      context = canvas.getContext('2d'),
      box     = new Rect(0, 0, 0, 0),
      center  = new Rect(0, 0, 0, 0),
      r       = new Rect(50, 50, 20, 20),
      r2      = new Rect(0, 0, 10, 10),
      rs      = RenderSystem.GetInstance(),
      resize  = function() {
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        
        box.w = innerWidth;
        box.h = innerHeight;
        
        center.x = ~~(innerWidth / 2);
        center.y = ~~(innerHeight / 2);
        
        context.fillStyle = '#ffffff';
        context.fillRect(0, 0, innerWidth, innerHeight);
      };
  
  // Create a strategy for our first square
  var moveStrat1: DiagonalMove = new DiagonalMove(r, new Vector2D(2, 1), box);
  
  // Create a renderable subject with the strategy for this instance
  var renderable1: MySubject   = new MySubject(r, moveStrat1);
  
  rs.AddRenderable(renderable1);
  
    // Create a new strategy for our new square
  var moveStrat2: CircularMove = new CircularMove(r2, center, 150);
  
  // Create a renderable subject with the strategy for this instance
  var renderable2: MySubject   = new MySubject(r2, moveStrat2);
  
  rs.AddRenderable(renderable1);
  rs.AddRenderable(renderable2);
  
  rs.Loop();
  
  window.addEventListener('resize', resize); resize();
})
              
            
!
999px

Console