Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw text on the top left corner of canvas

how do I write some text (with canvas.drawText?) ont the middle of the screen and on the left top corner? thank you (-:

like image 591
ihucos Avatar asked Jul 05 '11 17:07

ihucos


People also ask

How do you draw text on canvas?

Drawing Text on the Canvas To draw text on a canvas, the most important property and methods are: font - defines the font properties for the text. fillText(text,x,y) - draws "filled" text on the canvas. strokeText(text,x,y) - draws text on the canvas (no fill)

Which of the following method is use to write text on the canvas?

There are two methods fillText() and strokeText() to draw text on canvas.

Can you write on canvas HTML?

Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText().


2 Answers

I don't know why the above answer is marked with V when it's simply not correct. Drawing text at (0,0) will draw it off screen since, for some reason, the text is drawn from the bottom up (whereas everything else seem to be drawn from up to bottom).

If you want the top left corner:

paint = new Paint();
paint.setColor(Color.RED);
int fontSize = 20;
paint.setTextSize(fontSize);
Typeface tf = Typeface.create("FONT_NAME", Typeface.BOLD);
paint.setTypeface(tf);
paint.setTextAlign(Align.LEFT);
canvas.drawText("your_text", 0, (0+paint.getTextSize()), paint);
like image 186
Amit Farkash Avatar answered Sep 21 '22 20:09

Amit Farkash


using the ctx.textBaseline='top' it sets the position to the top then use ctx.textAlign='start' to position it to the left. example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Webpage</title>
        <link rel="stylesheet" href="style.css"/>
    </head>

    <body>
        <canvas id="gameCanvas"></canvas>
        <script>
        let canvas = document.getElementById('gameCanvas');
        let ctx = canvas.getContext('2d');
        canvas.height=window.innerHeight;
        canvas.width=window.innerWidth;
        ctx.fillStyle = 'rgb(0,0,0)';
        ctx.font = "15px Arial";
        ctx.textAlign='start';
        ctx.textBaseline='top';
        ctx.fillText("Hello World", 0, 0);
        </script>  
     </body>
</html>
like image 43
BatmanRealDa Avatar answered Sep 21 '22 20:09

BatmanRealDa