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

              
                <form id="inputs">
  <color-input id="bg" label="Background" value="#FF000066"></color-input>
  <color-input id="fg" label="Foreground" value="#0000FF66"></color-input>
</form>
<main-canvas id="main-canvas" canvas-width="400" canvas-height="220"></main-canvas>
              
            
!

CSS

              
                html,
body {
  height: 100%;
}

@media screen and (min-width: 600px) {
  body {
    align-items: center;
    display: flex;
    justify-content: center;
  }
}

              
            
!

JS

              
                import { ColorRGBA64, parseColorHexRGB, parseColorHexRGBA } from "https://unpkg.com/@microsoft/fast-colors";
import { attr, css, customElement, FASTElement, html, observable, ref, nullableNumberConverter } from "https://unpkg.com/@microsoft/fast-element";

@customElement({
  name: "color-input",
  template: html<ColorInput>`
    <template>
      <label class="control">
        <div>${(x) => x.label}</div>
        <input
          ${ref("colorPicker")}
          type="color"
          :value="${(x) => x.rgbvalue}"
          @input="${(x, c) => x.changeHandler(c.event as InputEvent)}"
        />
        <input
          ${ref("alphaRange")}
          type="range"
          min="0"
          max="1"
          step="0.05"
          @input="${(x, c) => x.changeHandler(c.event as InputEvent)}"
        />
      </label>
    </template>
  `,
  styles: css`
    :host {
      display: block;
      margin: 0 0 1rem;
    }

    .control {
      display: flex;
      flex-direction: column;
    }
    
    input {
      width: 100%;
    }
  `
})
export class ColorInput extends FASTElement {
  public alphaRange: HTMLInputElement;

  public colorPicker: HTMLInputElement;

  @attr
  public label: string;

  @attr
  public value: string;
  protected valueChanged(prev: unknown, next: string): void {
    this.rgbvalue = parseColorHexRGBA(next).toStringHexRGB();
  }

  @observable
  public color: ColorRGBA64;
  protected colorChanged(prev: ColorRGBA64 | unknown, next: ColorRGBA64): void {
    this.value = next.toStringHexRGBA();
  }

  @observable
  public rgbvalue: string;
  protected rgbvalueChanged(prev: string | unknown, next: string): void {
    if (this.$fastController.isConnected) {
      const color = this.color ?? parseColorHexRGBA(this.value);
      const { r, g, b } = color;
      const a = parseFloat(this.alphaRange.value);
      this.color = new ColorRGBA64(r, g, b, a);
      this.color = parseColorHexRGB(next);
    }
  }

  public changeHandler(e: InputEvent) {
    this.rgbvalue = this.colorPicker.value;
    const color = this.color ?? parseColorHexRGBA(this.value);
    const { r, g, b } = color;
    const a = parseFloat(this.alphaRange.value);
    this.color = new ColorRGBA64(r, g, b, a);
    mainCanvas.draw();
  }
}

@customElement({
  name: "copy-output",
  template: html<OutputTemplate>`
    <template>
      ${x => x.label}
      <input type="text" readonly :value="${x => x.value}" ${ref("output")}>
      <button @click="${x => x.clickHandler()}" ${ref("copy")}>
        ${x => x.buttonLabel}
      </button>
    </template>
  `,
})
export class OutputTemplate extends FASTElement {
  public output: HTMLInputElement;

  public copy: HTMLButtonElement;

  @attr
  public label: string;

  @attr({ attribute: "button-label" })
  public buttonLabel: string;

  @observable
  public value: string;

  public async clickHandler() {
    this.output.select();
    this.output.setSelectionRange(0, this.value.length);
    try {
      await navigator.clipboard.writeText(this.value);
    } catch (err) {
      console.log(err.message);
      document.execCommand("copy");
    }
  }
}

const checkerboard = new (class Checkerboard {
  public canvas: HTMLCanvasElement = document.createElement("canvas");
  public ctx: CanvasRenderingContext2D = this.canvas.getContext("2d")!;

  constructor() {
    this.canvas.width = 20;
    this.canvas.height = 20;
  }

  public draw() {
    this.ctx = this.canvas.getContext("2d")!;
    this.ctx.fillStyle = "#DFDFDF";
    this.ctx.fillRect(0, 0, 10, 10);
    this.ctx.fillRect(10, 10, 10, 10);

    this.project();
  }

  public project() {
    const ctx = mainCanvas.canvas.getContext("2d")!;
    ctx.fillStyle = ctx.createPattern(this.canvas, "repeat")!;
    ctx.fillRect(0, 0, mainCanvas.canvas.width, mainCanvas.canvas.height);
  }
})();

@customElement({
  name: "main-canvas",
  template: html`
    <template>
      <canvas ${ref("canvas")} width="${x => x.width}" height="${x => x.height}"></canvas>
      <label>
        <input
          type="checkbox"
          id="is-transparent"
          @input="${(x, c) => x.transparencyChanged(c.event as InputEvent)}"
          ?checked="${x => x.transparent}"
        />
        Transparent Canvas
      </label>
      <copy-output ${ref("output")} label="Mix:" button-label="copy to clipboard"></copy-output>
    </template>
  `,
  styles: css`
    canvas,
    label {
      display: block;
    }
    canvas {
      border: 1px solid #000;
      margin: 1rem;
    }
  `,
})
export class MainCanvas extends FASTElement {
  @attr({
    attribute: "canvas-width",
    converter: nullableNumberConverter
  })
  public width: number;

  @attr({
    attribute: "canvas-height",
    converter: nullableNumberConverter
  })
  public height: number;
  
  @observable
  public output: OutputTemplate;

  @observable
  public canvas: HTMLCanvasElement;

  @observable
  public transparent: boolean = true;
  
  public transparencyChanged(prev, next): void {
    this.transparent = !this.transparent;
    this.draw();
  }

  private x: number;
  private y: number;
  
  private bg = document.getElementById("bg") as ColorInput;
  private fg = document.getElementById("fg") as ColorInput;

  connectedCallback() {
    super.connectedCallback();
    this.draw();
  }

  get ctx(): CanvasRenderingContext2D {
    return this.canvas.getContext("2d") as CanvasRenderingContext2D;
  }

  public setDimensions() {
    this.canvas.width = this.canvas.scrollWidth;
    this.canvas.height = this.canvas.scrollHeight;
    this.x = ~~(this.canvas.width / 4);
    this.y = ~~(this.canvas.height / 2) - 24;
  }
  
  public async draw() {
    await new Promise(requestAnimationFrame);

    this.setDimensions();
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    if (this.transparent) {
      checkerboard.draw();
    } else {
      this.ctx.fillStyle = "#FFF";
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // Draw background box
    this.ctx.fillStyle = bg.value;
    this.ctx.fillRect(this.x + 12, this.y + 12, 48, 48);

    // Draw foreground box
    this.ctx.fillStyle = fg.value;
    this.ctx.fillRect(this.x - 12, this.y - 12, 48, 48);

    const data = this.ctx.getImageData(this.x + 24, this.y + 24, 1, 1).data;

    // Draw the mixed value
    const out = `rgba(${[
      ...data.slice(0, 3),
      parseFloat((Math.round((data[3] / 255) * 100) / 100).toFixed(2))
    ].join(", ")})`;
    this.ctx.fillStyle = out;
    this.ctx.fillRect(this.x * 2, this.y, 48, 48);

    // Color labels
    this.ctx.fillStyle = "#000";
    this.ctx.textAlign = "center";

    // Background color label
    this.ctx.textBaseline = "hanging";
    this.ctx.fillText(this.bg.value, this.x + 36, this.y + 72);

    // Foreground color label
    this.ctx.textBaseline = "bottom";
    this.ctx.fillText(this.fg.value, this.x + 6, this.y - 18);

    // Mix color label
    this.ctx.textBaseline = "middle";
    this.ctx.textAlign = "start";
    this.ctx.fillText(out, this.x * 2 + 54, this.canvas.height / 2);

    this.output.value = out;
  }
}

const mainCanvas = document.getElementById("main-canvas") as MainCanvas;
const inputs = document.getElementById("inputs") as HTMLFormElement;
inputs.addEventListener("change", () => requestAnimationFrame(() => mainCanvas.draw()));

              
            
!
999px

Console