Canvas and HTML5 ~ Moving Text from Left to Right

03.27

What is up, guys? Back with me again in this beautiful day. Today I will show you how to move text on canvas from left to right. First things first, let we together get a little bit understanding of what is the HTML5 and what is a <canvas>.

What is HTML5?


HTML5 is the latest version of Hypertext Markup Language, the code that describes web pages. It's actually three kinds of code: HTML, which provides the structure; Cascading Style Sheets (CSS), which take care of presentation; and JavaScript, which makes things happen.


What is HTML <canvas>?


The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.


In this tutorial, I am using my lovely Notepad++ v7.2.2 as the text editor and Mozilla Firefox as the browser. Alright! Have you get a grasp about what are we gonna do now? Are you ready for the real show ???.

Let's go!

1. Prepare the Canvas


First of all, open our text editor and we'll gonna start off with the basic HTML document. I'll give it the title of AgiaCanvas.


After that, we need to create our <canvas> tag inside the <body> tag and give the id a name, we can name it up to us, right now I chose to name it of AgiaCanvas with the width of 500 and height of 500.The width and height attribute is necessary to define the size of the canvas. 

When you set the element’s width and height attributes, you set both the element’s size and the size of the element’s drawing surface; however, when you use CSS to size a canvas element, you set only the element’s size and not the drawing surface. When the canvas element’s size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element. Because of this, it’s a good idea to use the canvas element’s width and height attributes to size the element, instead of using CSS. (Ivaylo Gerchev on Sitepoint)

By default, the canvas element has no border and no content. Note that anything that I've put inside the <canvas> tag is gonna show up if the browser doesn't support canvas. You can put an image or text there, provide a link, etc. This time, I'm just gonna put a text.


In order to do anything inside the canvas, we need to use Javascript. So, inside the <script> tag, we create a window.onload = funcRef;. The syntax is like in the picture below. That basically means that anything in between those two curly brackets will run when the entire page has loaded. Note : funcRef is the handler function to be called when the window's load event fires.


There are a few things we need to set up before we actually can draw the canvas. The JavaScript starts with two lines. The first line we create a variable named canvas which is a variable that caches our canvas element via its ID using the getElementById() method. The second line creates a variable (agia) that references the 2D context for the canvas using the getContext() function. We’ll use the agia variable to access all canvas drawing functions and properties. You can see the code below.


2. Prepare the Background


In order to prepare the background for the text, we need to color the canvas. Since the canvas is automatically a rectangle, we just need to draw a rectangle and the cover the entire canvas with it. To draw a rectangle, we can use the fillRect(x, y, width, height) method to set the coordinates and the dimensions, along with the fillStyle property to set the fill color. I set the color to be blue and it start from the very first coordinates (0,0) and with the width and height of the canvas. We can make it sure that the 500 x 500 px canvas filled with blue.


The fillStyle is sort like choosing your paint bucket tool's color, and the fillRect takes in 4 arguments, which is the first two are x and y location (the coordinates) for where to start filling the rectangle and we have the width and height argument for the width and height of the rectangle. The result will be like this picture below.



3. Create the text


To draw text on the canvas, we can use fillText(string, x, y) along with the font property to set the font, size, and style of the text (similar to font shorthand in CSS).


Now, we can set the text's font by saying agia.font = "50px Arial";, which means that I use the Arial as a font with the size of 50 pixels. The fillStyle there is to give the text a color of white. The agia.fillText("AGIA", 200, 200); means that we have text "AGIA" and write and the x and y location for it, which is 200 each of them. The result will be like this below.


Are you still confused with the x and y location??? Let we elaborate it together!

The 2d rendering context is a standard screen-based drawing platform. Like other 2d platforms, it uses a flat Cartesian coordinate system with the origin (0, 0) at the top left. Moving to the right will increase the x value, and moving downwards will increase the y value. Understanding how the coordinate system works is integral if you want to have things draw in the right place. 

A single unit in the coordinate system is usually equivalent to 1 pixel on the screen, so the position (200, 200) would be 200 pixels right and 200 pixels down. There are some occasions where a unit in the coordinate system might equal 2 pixels, like with high definition displays, but the general rule of thumb is that 1 coordinate unit equals 1 screen pixel. (Explanation on CreativeBloq)

courtesy : sitepoint.com


4. Move the text from left to right


If we wanna animate the text, we need to get a setInterval(). In this picture below, it will run the anonymous function every 40 miliseconds, which is about 40 frames per second. 

Let's say if we want to animate over the blue canvas. We can copy the background code and that means it will continously paint the blue canvas every 40 miliseconds. Then, we take our text code to the function. And it won't animating, but it means it's being drawn and painted again and again and again over top of the blue background.


To animate, we need a variable outside the setInterval(), let's call it start, and set it equals to 0 (zero). And in the x position argument of the text code, we insert the start variable. And at the top, we type start += 4, which means it'll animates/moves across the screen from left to right every 4 ms (note: if you want to make the text moves faster, you can change the number to the greater one, and if you want it moves slower, just decrease the value). Below are the screenshot and the animated GIF of the moving text. To get a better experience, you can try to download the html file on this Userscloud Link




Anyway, are you still confused with the setInterval() ???
Let elaborate it a little bit.

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed. The ID value returned by setInterval() is used as the parameter for the clearInterval() method. (Explanation on W3Schools

Alright! That's all I can present to you, now. Thanks for your attention and see you in the future. Anyway, you can see the full code in the last section of this web. Gracias~

To learn more about the <canvas> on HTML5, you can visit :

- HTML5 Canvas Tutorials

- Developer Mozilla

- Only Web Pro

- Tutsplus  


THE CODE


<!DOCTYPE html>
<html>
<title>AgiaCanvas</title>
<body>
<canvas id="AgiaCanvas" width="500" height="500">
Hey, bro. Get a Firefox/Chrome!
</canvas>
<script>
window.onload = function(){
var canvas = document.getElementById("AgiaCanvas"),
agia = canvas.getContext("2d");

agia.fillStyle = "blue";
agia.fillRect(0, 0, canvas.width, canvas.height);

agia.fillStyle = "white";
agia.font = "50px Arial";
agia.fillText("AGIA", 200, 200);

var start = 0;
setInterval(function(){

start += 4;

agia.fillStyle = "blue";
agia.fillRect(0, 0, canvas.width, canvas.height);

agia.fillStyle = "white";
agia.font = "50px Arial";
agia.fillText("AGIA", start, 200);

}, 40);
};
</script>
</body>
</html>

You Might Also Like

4 komentar

  1. admin numpang promo ya.. :)
    cuma di sini tempat judi online yang aman dan terpecaya di indoneisa
    banyak kejutan menang
    agent judi online dengan proses cepat kurang dari 2 menit :)
    ayo segera bergabung di fansbetting
    F4ns Bett1ng agen judi online aman dan terpercaya
    Jangan ragu, menang berapa pun pasti kami proseskan..
    B0l4, C4sin0, s4bun9 4yam, T0gel dll.. dp50 wd50
    Silakan di add ya teman" WA : +855963156245^_^

    BalasHapus
  2. mau untung banyak tanpa kerja?
    solusinya yaitu zeusbola!
    dengan deposit minimal Rp 50.000 kamu sudah bisa menjadi member kami dan bisa bermain berbagai banyak jenis game dengan 1 user id saja
    ???keuntungannya tidak main main???
    lansung gas untuk daftar ya bosquww

    terdapat beberapa jenis bank lokal yang bisa digunakan bermain di
    zeusbola seperti :






    UNTUK INFORMASI LEBIH LANJUT SILAHKAN HUBUNGI KAMI DI:
    WHATSAPP : +62 822-7710-4607
    FACEBOOK : @zeusbolame
    LINE : zeusbola
    INSTAGRAM : zeusbola.official

    BalasHapus
  3. Selamat datang di BOLAVITA JUDI ONLINE TERBAIK DI INDONESIA

    BOLAVITA akan memberikan kenyamanan dan keamanan untuk semua member BOLAVITA !!

    Keuntungan dalam bermain di website BOLAVITA :
    > Proses deposit dan withdraw maksimal 2 menit
    > 100% PLAYER vs PLAYER
    > MURNI FAIRPLAY
    > Sistem keamanan terjamin terbaik
    > CUSTOMER SERVICE 24 JAM NONSTOP

    Dapatkan juga bonus-bonus yang menarik :
    > BONUS NEW MEMBER 10%
    > BONUS EVERY DAY 5%
    > BONUS REFERRAL UP TO 10%

    TERSEDIA DEPOSIT VIA :
    => PULSA ( XL & TELKOMSEL )
    => E-wallet (OVO, LINK AJA, GO-PAY, JENIUS dan DANA)
    => Bank (BCA, BRI, BNI, MANDIRI, CIMB NIAGA dan DANAMON)

    KLIK DISINI UNTUK MENDAFTAR BOLAVITA

    Untuk informasi lebih lanjut bisa hubungi kami via livechat ataupun :
    ✔ WA / TELEGRAM : +62812-2222-995
    ✔ INSTAGRAM : @bola.vita
    ✔ FACEBOOK : @bolavita.ofc

    BalasHapus
  4. Lucky Eagle Casino Resort and Spa - JTM Hub
    This resort 광명 출장샵 is located 부천 출장안마 off 천안 출장마사지 the Las Vegas strip, close 문경 출장샵 to a pedestrian bridge and on 인천광역 출장마사지 a scenic footpath. Experience luxurious accommodations,

    BalasHapus