Tag Archives: Text inside Shapes in Canvas HTML5

Add text to Shapes in Canvas HTML5.

Write the javascript part in the head section of the html page.

<script>function Draw_Rectangle(Canvas, Left_Position, Top_Position, Width, Height, Line_Color, LINE_WIDTH, FillColor, text) {
var Context2d = Canvas.getContext('2d');
if (Context2d) {
    //Draw Rectangle
    Context2d.strokeStyle = Line_Color;
    Context2d.lineWidth = LINE_WIDTH;
    Context2d.fillStyle = FillColor;
    Context2d.fillRect(Left_Position, Top_Position, Width, Height);
    Context2d.strokeRect(Left_Position, Top_Position, Width, Height);
    //Add Text to Rectangle
    Context2d.textBaseline = 'middle';
    Context2d.font = '8px Arial';
    Context2d.fillStyle = 'white';
    var textX = Left_Position + Width / 2 - Context2d.measureText(text).width / 2;
    var textY = Top_Position + Height / 2;
    Context2d.fillText(text, textX, textY);

Write the html part in the body section of the html page.

<canvas id='Canvas' width='500' height='500'></canvas>
<script>Draw_Rectangle(Canvas, 100, 100, 100, 50, '#FFFFFF', 1, '#6ed629', 'CodeSolution.org');</script>

HTML5 Canvas Rectangle With Text

HTML5 Canvas Rectangle With Text