Drawing with Text Using HTML5 Canvas

Drawing with Text Using HTML5 Canvas
Code Snippet:Drawing with text
Author: Tim Holman
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 372
License: MIT
Edit Code online: View on CodePen
Read More

This code snippet helps you to create a simple drawing tool that lets you draw with text using an HTML5 canvas. Click, drag, and release to create artistic text-based drawings. It allows you to draw using a string of text characters, creating unique visual outputs. It’s helpful for artistic expression and experimenting with text-based designs.

You can use this code to add an interactive and creative drawing feature to your website. It’s ideal for artistic expression, letting users draw with text in a visually engaging way.

How to Draw with Text Using HTML5 Canvas and JS

1. First of all, include a canvas element in your HTML where the drawing will take place.

<canvas id='canvas'></canvas>
<span id='info'>Click and drag to draw!<span>

<!-- 
  Drawing with text:
  
  -  Click and drag to draw.
  -  Double click to clear.

  Ported from java at http://www.generative-gestaltung.de

  by Tim Holman - @twholman

-->

2. Apply necessary CSS styles to the canvas and span elements. This ensures proper positioning and appearance of the drawing canvas and instructions.

html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
  overflow: hidden;
}
html:hover span, body:hover span {
  display: none;
}

canvas {
  cursor: crosshair;
}

span {
  font-family: 'Georgia', cursive;
  font-size: 40px;
  position: fixed;
  top: 50%;
  left: 50%;
  color: #000;
  margin-top: -40px;
  margin-left: -200px;
}

3. Finally, copy the following JavaScript code into a separate script file or within <script></script> tags within your HTML document. This code handles the drawing functionality.

Modify the letters variable to use different text for drawing. Adjust the minFontSize and angleDistortion variables to alter the drawing’s appearance.

// Drawing with text. Ported from Generative Design book - http://www.generative-gestaltung.de - Original licence: http://www.apache.org/licenses/LICENSE-2.0

// Application variables
var position = {x: 0, y: window.innerHeight/2};
var counter = 0;
var minFontSize = 3;
var angleDistortion = 0;
var letters = "There was a table set out under a tree in front of the house, and the March Hare and the Hatter were having tea at it: a Dormouse was sitting between them, fast asleep, and the other two were using it as a cushion, resting their elbows on it, and talking over its head. 'Very uncomfortable for the Dormouse,' thought Alice; 'only, as it's asleep, I suppose it doesn't mind.'";

// Drawing variables
var canvas;
var context;
var mouse = {x: 0, y: 0, down: false}

function init() {
  canvas = document.getElementById( 'canvas' );
  context = canvas.getContext( '2d' );
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  
  canvas.addEventListener('mousemove', mouseMove, false);
  canvas.addEventListener('mousedown', mouseDown, false);
  canvas.addEventListener('mouseup',   mouseUp,   false);
  canvas.addEventListener('mouseout',  mouseUp,  false);  
  canvas.addEventListener('dblclick', doubleClick, false);
  
  window.onresize = function(event) {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }
}

function mouseMove ( event ){
  mouse.x = event.pageX;
  mouse.y = event.pageY;
  draw();
}

function draw() {
 if ( mouse.down ) {
    var d = distance( position, mouse );
    var fontSize = minFontSize + d/2;
    var letter = letters[counter];
    var stepSize = textWidth( letter, fontSize );
    
    if (d > stepSize) {
      var angle = Math.atan2(mouse.y-position.y, mouse.x-position.x);
      
      context.font = fontSize + "px Georgia";
    
      context.save();
      context.translate( position.x, position.y);
      context.rotate( angle );
      context.fillText(letter,0,0);
      context.restore();

      counter++;
      if (counter > letters.length-1) {
        counter = 0;
      }
    
    //console.log (position.x + Math.cos( angle ) * stepSize)
      position.x = position.x + Math.cos(angle) * stepSize;
      position.y = position.y + Math.sin(angle) * stepSize;

      }
  }     
}

function distance( pt, pt2 ){
  
  var xs = 0;
  var ys = 0;
 
  xs = pt2.x - pt.x;
  xs = xs * xs;
 
  ys = pt2.y - pt.y;
  ys = ys * ys;
 
  return Math.sqrt( xs + ys );
}

function mouseDown( event ){
  mouse.down = true;
  position.x = event.pageX;
  position.y = event.pageY;
  
  document.getElementById('info').style.display = 'none';
}

function mouseUp( event ){
    mouse.down = false;
}

function doubleClick( event ) {
  canvas.width = canvas.width; 
}

function textWidth( string, size ) {
  context.font = size + "px Georgia";
  
  if ( context.fillText ) {
    return context.measureText( string ).width;
  } else if ( context.mozDrawText) {
    return context.mozMeasureText( string );
  }
  
 };

init();

Change the canvas size by adjusting the canvas.width and canvas.height properties.

That’s all! hopefully, you have successfully created Drawing With Text Using HTML5 Canvas. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X