Category Archives: HTML

HTML Canvas stretches my drawings

Ever made a paint program with the canvas element only to get your drawings stretched over the canvas? This is due to a “feature” in certain browsers. To get around this you need to specify the height and width INSIDE the canvas element. Specifying it in a STYLE tag or CSS class will not work. So this will NOT work

  <canvas id="mycanvas" style="height:300px;width:400px" >

or this

  <canvas id="mycanvas" class="heightandwidth" >

But this will

  <canvas id="mycanvas" height="300" width="400" >

Tested on OSX 10.12.5 and Chrome 58.0.3029.110 (64-bit)

Embed pictures in HTML code with Base64 encoding

There are times when you do not want to reference a picture on a HTML page but you want the picture to be IN the HTML code. This can for example be if you are creating HTML to send in e-mails. Attaching a bunch of picture files does not always go well with mail software and spam filters.

The secret here is the “hidden” talents of the img tag which can read base64 encoded content. The syntax is:

<img src="data:{mime};base64,{data}" alt="My picture"/>

{Mime} is in ‘image/imagetype’ format (eg. ‘image/jpg’ or image/png) and {data} is the base64 encoded string

<img src="data:image/gif;base64, iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAIAAACdjxhxAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGF
 alt="Flag of Sweden"/>

Here the mime is ‘image/gif’ since the picture data is from a gif file. You can also use image/png and image/jpg.
When running the code above through a browser we get:
Flag of Sweden

A small picture of the flag of Sweden. Not much, but base64 encoded pictures tend to be quite large in string form 🙂

Tested on OS X 10.6.8 and Chrome 16 Beta