How to set text alignment using html5 Canvas

HTML5 Canvas text alignment tutorial

how to set textalignment using html5canvas

In this html5 Canvas tutorial we will dicuss how to set text alignment using htm5 Canvas. Moreover In Html5 canvas , we used textAlign property to set the text alignment on the canvas. textAlign property can takes these following 5 values.

  1. start
  2. end
  3. left
  4. right
  5. center

Default value is start.

1.  start

Similarly In this case the text is aligned at the normal start of line. However If text is aligned left to right text is at the left end, if text is aligned from right to left, then text is placed at the right.

2.  end

Similarly In this case the text is aligned at the normal end of the line. However for left to right aligned text the text will be at the right end of line and for right to left aligned, Moreover the text will be at the left end.

3.  left

Moreover The text is left-aligned.

4.  Right

However the text is right-aligned.

5.  center

Similarly The text is centered.
However The syntax for setting text alignment is given below.


Context.textAlign = value;


HTML5 Canvas text Alignment complete code example


<!DOCTYPE html>
        <title>how to set text alignment using html5 Canvas </title>
        <canvas id ="myCanvas" width ="600" height ="400"
            style="border: 1px solid blue;" >
            var  canvas = document.getElementById("myCanvas");
            var context =canvas.getContext('2d');
            var x = canvas.width / 2;
            var y = canvas.height / 2;

            context.font = '30pt Calibri';
            context.textAlign = 'center';
            context.fillStyle = 'blue';
            context.fillText('Hello HTML5 Canvas!', x, y);


HTML5 Canvas Text Alignment


html5 Canvas text alignment tutorial


Live demo HTML5 Canvas text alignment on codepen

[codepen_embed height=500 theme_id=1 slug_hash=’VYxvEy’ user=’aslamwaqar’ default_tab=’html’


Next Lecture How to Draw 2d text using html5

Author: Habibullah Qamar

Its me Habib Ullah Qamar working as a Lecturer (Computer Sciences) in Pakistan. I have an MS(M.Phil) degree in computer sciences with specialization in software engineering from Virtual University of Pakistan Lahore. I have an experience of more than 15 years in the filed of Computer Science as a teacher. Blog Writing is my passion. I have many blogs, This one is special made with the aim of providing 100% Free online coaching and training to the students of under-graduate and postgraduate classes. Most of the students enrolled in computer sciences, information technology, software engineering and related disciplines find it difficult to understand core concepts of programming and office automation. They find difficult in understanding and solving their assignments.

Leave a Reply

Your email address will not be published. Required fields are marked *