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

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                const config = {
  characterSet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-ⅠⅡ←→[]?()/+',
  characterWidth: 7,
  characterHeight: 7,
  horizontalSpacing: 1,
  verticalSpacing: 1,
  columnCount: 10,
  rowCount: 5,
};

const destinationCanvas = document.createElement('canvas');
destinationCanvas.width = 320;
destinationCanvas.height = 200;
destinationCanvas.style.border = '1px solid gray';
document.body.appendChild(destinationCanvas);

const destinationContext = destinationCanvas.getContext('2d');
destinationContext.imageSmoothingEnabled = false;

const intermediaryCanvas = document.createElement('canvas');
intermediaryCanvas.style.border = '1px solid brown';
intermediaryCanvas.width = 0;
intermediaryCanvas.height = 0;

// Comment out next line in production
document.body.appendChild(intermediaryCanvas);

const image = new Image();
image.crossOrigin = 'anonymous';
image.addEventListener('load', () => {
  const redOffset = generateColor(image, intermediaryCanvas, 'red');
  const greenOffset = generateColor(image, intermediaryCanvas, 'green');
  const blueOffset = generateColor(image, intermediaryCanvas, 'blue');
  
  const redFont = new SpriteFont(
    intermediaryCanvas,
    destinationCanvas,
    config,
    {scale: 3, offset: redOffset }
  );
  const greenFont = new SpriteFont(
    intermediaryCanvas,
    destinationCanvas,
    config,
    {scale: 3, offset: greenOffset }
  );
  const blueFont = new SpriteFont(
    intermediaryCanvas,
    destinationCanvas,
    config,
    {scale: 3, offset: blueOffset }
  );
  
  
  redFont.drawText('THE DOG BARKS', { x: 10, y: 20 });
  greenFont.drawText('VERY LOUDLY', { x: 10, y: 60 });
  blueFont.drawText('AT THE FENCE', { x: 10, y: 100 });  
});
image.src = 'https://i.imgur.com/i4mFBB5.png';

function generateColor(image, intermediaryCanvas, color) {
  const intermediaryContext = intermediaryCanvas.getContext('2d');

  const offsetX = 0;
  const offsetY = intermediaryCanvas.height;
  
  let prevImageData = null;
  if (intermediaryCanvas.width > 0 && intermediaryCanvas.height > 0) {
    prevImageData = intermediaryContext.getImageData(
      0,
      0,
      intermediaryCanvas.width,
      intermediaryCanvas.height,
    );
  }
  
  intermediaryCanvas.width = image.naturalWidth;
  intermediaryCanvas.height = intermediaryCanvas.height + image.naturalHeight;

  intermediaryContext.drawImage(image, offsetX, offsetY);

  intermediaryContext.globalCompositeOperation = 'source-in';
  intermediaryContext.fillStyle = color;
  intermediaryContext.fillRect(offsetX, offsetY, image.naturalWidth, image.naturalHeight);
  intermediaryContext.globalCompositeOperation = 'source-over';
  
  if (prevImageData !== null) {
    intermediaryContext.putImageData(prevImageData, 0, 0);
  }
  
  const offset = {
    x: offsetX,
    y: offsetY,
  };
  
  return offset;
}

class SpriteFont {
  
  static DEFAULT_OPTIONS = {
    scale: 1,
    characterSpacing: 1,
    lineSpacing: 10,
    align: 'left',
    offset: { x: 0, y: 0 },
  };
  
  constructor(sourceImage, destinationCanvas, config, options = {}) {
    this.sourceImage = sourceImage;
    
    this.destinationCanvas = destinationCanvas;
    this.destinationContext = destinationCanvas.getContext('2d');
    
    this.config = config;
    
    this.options = Object.assign({}, SpriteFont.DEFAULT_OPTIONS, options);
  }
  
  drawCharacter(character, position = { x: 0, y: 0 }) {
    const characterIndex = this.config.characterSet.indexOf(character);

    if (characterIndex === -1) {
      throw new Error(`Font character "${character}" is not defined`);
    }

    const rowIndex = Math.floor(characterIndex / this.config.columnCount);
    const columnIndex = characterIndex % this.config.columnCount;

    const {
      characterWidth,
      characterHeight,
      horizontalSpacing,
      verticalSpacing,
    } = this.config;
    
    const { offset } = this.options;
    
    const sourceX = offset.x + columnIndex * (characterWidth + horizontalSpacing);
    const sourceY = offset.y + rowIndex * (characterHeight + verticalSpacing);
    const sourceWidth = characterWidth;
    const sourceHeight = characterHeight;

    const destinationX = position.x;
    const destinationY = position.y;
    const destinationWidth = characterWidth * this.options.scale;
    const destinationHeight = characterHeight * this.options.scale;

    this.destinationContext.drawImage(
      this.sourceImage,
      sourceX, sourceY, sourceWidth, sourceHeight,
      destinationX, destinationY, destinationWidth, destinationHeight
    );
  }

  drawWord(word, position = { x: 0, y: 0 }) {
    const characters = this.splitWordIntoCharacters(word);

    characters.forEach((character, characterIndex) => {
      let characterSpacing = this.options.characterSpacing;
      if (characterIndex === 0) {
        characterSpacing = 0;
      }

      const characterTotalWidth = this.config.characterWidth * this.options.scale + characterSpacing;

      const characterX = position.x + characterIndex * characterTotalWidth;
      const characterY = position.y;

      const characterPosition = {
        x: characterX,
        y: characterY,
      };

      this.drawCharacter(character, characterPosition);
    });
  }

  drawLine(line, position = { x: 0, y: 0 }) {
    const words = this.splitLineIntoWords(line);

    let prevWordEndX = 0;

    words.forEach((word, wordIndex) => {
      const wordX = position.x + prevWordEndX;
      const wordY = position.y;
      const wordPosition = {
        x: wordX,
        y: wordY,
      };

      this.drawWord(word, wordPosition);

      const wordWidth = this.getWordWidth(word);

      let wordSpacing = this.getWordSpacing();
      if (wordIndex === words.length - 1) {
        wordSpacing = 0;
      }

      const wordTotalWidth = wordWidth + wordSpacing;

      prevWordEndX += wordTotalWidth;
    });
  }

  drawText(text, position = { x: 0, y: 0 }) {
    const textWidth = this.getTextWidth(text);

    const lines = this.splitTextIntoLines(text);

    lines.forEach((line, lineIndex) => {
      let lineSpacing = this.options.lineSpacing;
      if (lineIndex === 0) {
        lineSpacing = 0;
      }

      const lineWidth = this.getLineWidth(line);
      
      let lineX = position.x;
      if (this.options.align === 'center') {
        lineX += (textWidth - lineWidth) / 2;
      } else if (this.options.align === 'right') {
        lineX += textWidth - lineWidth;
      }

      const lineTotalHeight = this.config.characterHeight * this.options.scale + lineSpacing;

      const lineY = position.y + lineTotalHeight * lineIndex;

      const linePosition = {
        x: lineX,
        y: lineY,
      };

      this.drawLine(line, linePosition);
    });
  }

  splitWordIntoCharacters(word) {
    return Array.from(word);
  }

  splitLineIntoWords(line) {
    return line.split(' ');
  }

  splitTextIntoLines(text) {
    return text.split('\n');
  }

  getWordWidth(word) {
    const allCharactersWidth = word.length * (config.characterWidth * this.options.scale);
    const allSpacingsWidth = (word.length - 1) * this.options.characterSpacing;

    const wordWidth = allCharactersWidth + allSpacingsWidth;

    return wordWidth;
  }

  getWordSpacing() {
    return this.config.characterWidth * this.options.scale + this.options.characterSpacing * 2
  }

  getLineWidth(line) {
    let lineWidth = 0;

    const words = this.splitLineIntoWords(line);

    words.forEach((word, wordIndex) => {
      const wordWidth = this.getWordWidth(word);

      let wordSpacing = this.getWordSpacing();
      if (wordIndex === 0) {
        wordSpacing = 0;
      }

      const wordTotalWidth = wordWidth + wordSpacing;

      lineWidth += wordTotalWidth;
    });

    return lineWidth;
  }

  getTextWidth(text) {
    const lines = this.splitTextIntoLines(text);

    const lineWidths = lines.map((line) => {
      return this.getLineWidth(line);
    });

    const maxLineWidth = Math.max(...lineWidths);

    return maxLineWidth;
  }
}

              
            
!
999px

Console