logo of blechtrottel.net blechtrottel.net
Deutsch

RSS logo with <canvas>

News format RSS is not as popular as it was a few years ago. The more informative and technical a website, the more likely it is to find the RSS logo there, which was introduced by Mozilla.

HTML5 is widespread in the WWW nowadays. Many of the new things it brought along are supported by all browsers. The new element <canvas> is very interesting, for example, as it allows drawing.

In this article we will use this new element to draw a RSS logo. And that without any image file.

Remarks

We expect you to have a basic knowledge of both HTML and JavaScript.

Our logo is 24x24 pixels in size, to make things easier to see it is displayed at 48x48. For matters of comparison you will find the original gif at the same size in front of it.

Canvas

First of all we add a <canvas> element to our HTML:

<canvas id="rss" width="24" height="24"></canvas>

It is important to have an id attribute (id="rss") here, so that the JavaScript that does the actual drawing can find the canvas. There is nothing to see here, yet. The canvas is transparent, so at the moment it is hidden from view.

JavaScript

Let us add a JavaScript block and write a function named draw():

<script type="text/javascript">
function draw(){
  var canvas = document.getElementById('rss');
  if (canvas.getContext){
    var ctx = canvas.getContext('2d');
  }
}
</script>

In the lines listed above we first search for the canvas by its id and make sure that our browser actually supports the code needed for our further work. For the time being, drawing in 3D ('3d') is not intended to become part of HTML5.

Drawing

Our logo needs an orange background. Via CSS we can only give the canvas element a border not a background, therefore we have to draw a rectangle that is the same size as the canvas. It spreads from top left (0,0) to bottom right (24,24):

ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(0,0,24,24);

The lines we define as quarter circles in white. They share the same center (4,21) and differ in radius (15 and 10).

ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(4,21,15,Math.PI*3/2,0,false);
ctx.moveTo(4,11);
ctx.arc(4,21,10,Math.PI*3/2,0,false);
ctx.moveTo(8,18);
ctx.arc(7,18,1,Math.PI*2,0,false);
ctx.stroke();

At the end we define a the dot as a circle with a tiny radius (1). The Math.PI in the code refers to starting and end points of the circle lines. They have to be given as angles in Radian (rad). Math.PI*3/2 is the top, 0 is right and our end point. Details to the Radian unit can be found at Wikipedia.

The last argument in the brackets is the anticlockwise property. In our case it is false, as we will draw our quarter circles from top to right (= clockwise). The ctx.moveTo() keeps our lines separated. Without it there would be lines joining the end point of one line to the starting point of the next.

nextPart1 - Part2