HTML 5 is a software solution stack that defines the properties and behaviors of web page content by implementing a markup based pattern to it. HTML 5 is the fifth and current major version of the HTML standard, and subsumes XHTML
Sean Robertson

Sean Robertson


HTML Canvas | Draw Text on HTML5 Canvas with JavaScript

How to Draw Text on HTML5 Canvas Using JavaScript

In today's video I'll show you how easy it is to draw text on the HTML5 canvas using JavaScript. We take a look at filling text, outlined text and centering text.

For your reference, check this out: 

Draw text on an HTML canvas using JavaScript

Learn how to use the HTML5 canvas element to draw and style text

The canvas element (new to HTML5) is used to draw 2D graphics into an HTML document. Using Javascript you can draw a wide range of objects into an HTML canvas such as lines, text, images and shapes using several built in functions. Drawing text on an HTML5 canvas is a useful ability that you can use to add extra information to any data, images or shapes you have previously drawn on your canvas.

Adding a canvas to your HTML document and interacting with it in Javascript

To use Javascript to interact with an HTML canvas, you will first need to add the canvas element into your HTML document like so:

<canvas id="testCanvas" width="200" height="200">           

In this example we give the canvas a fixed width and height to make it easier to keep track of co-ordinates. This canvas will be used throughout the tutorial.

Once the canvas element has been added to your HTML document, you must then acquire a context object from it by retrieving the canvas element and calling the getContext("2d") method.

var canvas = document.getElementById("testCanvas");           
var context = canvas.getContext("2d");         

With the context object you can call certain functions that will allow you to draw objects to the canvas.

Drawing text onto your HTML canvas using Javascript

Once the 2D context object has been acquired you can start drawing text onto your HTML canvas. Drawing text can either be done using the fillText() method or the strokeText() method of the context object.

Both the fillText() and strokeText() methods take 4 arguments (of which 3 are required):

  • text: A string value containing the text you wish to draw to the canvas
  • X: The X coordinate of where to start drawing the string to your canvas
  • Y: The X coordinate of where to start drawing the string to your canvas
  • max-width (optional) : The maximum pixel width of drawn text

The main difference between the two methods is that strokeText() will only draw the outlines for each letter whereas fillText() will also fill the inside of the text.

Drawing text using the fillText() method:

var canvas = document.getElementById( "testCanvas" );   
var context = canvas.getContext( "2d" );   
// change font and font-size for better visibilty   
context.font = "30px Impact";    
// draw "Test text" at X = 10 and Y = 30   
context.fillText( "Test text", 10, 30 );

The text drawn to the canvas will look like this:


Drawing text to an HTML canvas using fillText()


Drawing text using the strokeText() method:

var canvas = document.getElementById( "testCanvas" );   
var context = canvas.getContext( "2d" );   
// change font and font-size for better visibilty   
context.font = "30px Impact";    
// draw "Test text" at X = 10 and Y = 30   
context.strokeText( "Test text", 10, 30 );

The text drawn to the canvas will look like this:


Drawing text to an HTML canvas using strokeText()


Styling your text before drawing it onto your canvas

There are several properties of the 2D context object that you can use to change the appearance and style of the text you draw to your canvas.

Changing the font and font-size :

To change the font and font-size you can make use of the font property of the context object, simply provide a font-size in pixels and the name of the font you want to use such as Verdana.

var canvas = document.getElementById( "testCanvas" );   
var context = canvas.getContext( "2d" );   
// change font and font-size for better visibilty   
context.font = "40px Verdana";    
// draw "Test text" at X = 10 and Y = 30   
context.fillText( "Test text", 10, 30 );

The text drawn to the canvas will look like this:


Changing font and font-size before drawing to canvas


Changing the font color: The fillStyle property of the context object can be used to change the color of the text (it can also add a gradient or pattern). To change the color using this property, simply give a valid HTML color as a value.

var canvas = document.getElementById( "testCanvas" );   
var context = canvas.getContext( "2d" );   
// change font and font-size for better visibilty   
context.font = "30px Impact";    
// change font color    
context.fillStyle = "red";    
// draw "Test text" at X = 10 and Y = 30   
context.strokeText( "Test text", 10, 30 );

The text drawn to the canvas will look like this:


Changing font color before drawing to canvas


Changing the alignment of your text: By using the textAlign property of the context object, you can change the alignment of your text relative to the given X position given for fillText() or strokeText(). There are several values from which you can choose:

  • start: Drawn text will begin at the given X position
  • end: Drawn text will end at the given X position
  • left: The starting point for text will be to its left (essentially the same as start)
  • right: The ending point for text will be to its right (essentially the same as end)
  • center: Drawn text will center itself around the given X position

As an example, let's create a canvas with text using each of these values and the same X point.

var canvas = document.getElementById( "testCanvas" );   
var context = canvas.getContext( "2d" );   
// change font and font-size for better visibilty   
context.font = "30px Arial";    
// draw each string with same X value but different alignment   
context.textAlign = "start";   
context.fillText( "start", 80, 30 );    
context.textAlign = "end";   
context.fillText( "end", 80, 60 );    
context.textAlign = "left";   
context.fillText( "left", 80, 90 );    
context.textAlign = "right";   
context.fillText( "right", 80, 120 );    
context.textAlign = "center";   
context.fillText( "center", 80, 150 );

The text drawn to the canvas will look like this:


Changing text alignment before drawing to canvas



#html #html5 #javascript

HTML Canvas | Draw Text on HTML5 Canvas with JavaScript

James Wilhelm



In this tutorial, we cover cover how to create a new HTML element dynamically in JavaScript using document.createElement(), and set attributes for the new element using element.setAttribute(), such as ID and class.
#javascript #javascript_tutorial #tutorial #webdevelopment #webdev #frontend #frontenddeveloper #programming #html5

🔔 Subscribe for more tutorials just like this one:

🔗 Visit our website:


Go-canvas: Library to Use HTML5 Canvas From Go-WASM


go-canvas is a pure go+webassembly Library for efficiently drawing on a html5 canvas element within the browser from go without requiring calls back to JS to utilise canvas drawing functions.

The library provides the following features:

  • Abstracts away the initial DOM interactions to setup the canvas.
  • Creates the shadow image frame, and graphical Context to draw on it.
  • Initializes basic font cache for text using truetype font.
  • Sets up and handles requestAnimationFrame callback from the browser.


go-canvas takes an alternate approach to the current common methods for using canvas, allowing all drawing primitives to be done totally with go code, without calling JS.

standard syscall way

In a standard WASM application for canvas, the go code must create a function that responds to requestAnimationFrame callbacks and renders the frame within that call. It interacts with the canvas drawing primitives via the syscall/js functions and context switches. i.e.

laserCtx.Call("arc", gs.laserX, gs.laserY, gs.laserSize, 0, math.Pi*2, false)

Downsides of this approach (for me at least), are messy JS calls which can't easily be checked at compile time, forcing a full redraw every frame, even if nothing changed on that canvas, or changes being much slower than the requested frame rate.

go native way

go-canvas allows all drawing to be done natively using Go by creating an entirely separate image buffer which is drawn to using a 2D drawing library. I'm currently using one from which provides most of the standard canvas primitives and more. This shadow Image buffer can be updated at whatever rate the developer deems appropriate, which may very well be slower than the browsers animation rate.

This shadow Image buffer is then copied over to the browser canvas buffer during each requestAnimationFrame callback, at whatever rate the browser requests. The handling of the callback and copy is done automatically within the library.

Secondly, this also allows the option of drawing to the image buffer, outside of the requestAnimationFrame callback if required. After some testing it appears that it is still best to do the drawing within the requestAnimationFrame callback.

go-canvas provides several options to control all this, and take care of the browser/dom interactions

  • User specifies the go render/draw callback method when calling the START function. This callback passes the graphical context to the render routine.
  • Render routine can choose to return whether any drawing took place. If it returns false, then the requestAnimationFrame callback does nothing, just returns immediately, saving CPU cycles. (No point to copy buffers and redraw if nothing has changed) This allows the drawing to be adaptive to the rate of data changes.
  • The 'start' function accepts a maxFPS parameter. The library will automatically throttle the requestAnimationFrame callback to only do redraws or image buffer copies to this max rate. Note it MAY be slower depending on the Render time, and the requirements of the browser doing other work. When a tab is hidden, the browser regularly reduces and may even stop call to the animation callback. No critical timing should be done in the render/draw routings.
  • You may pass 'nil' for the render function. In this case all drawing happens totally under the users control, outside of the library. This may be more useful in future when WASM supports proper threading. Right now however, testing shows it is slower as all work is in the one thread, and you lose the scheduling benefits of the requestAnimationFrame call.

Drawing therefore, is pure go. i.e.

func Render(gc *draw2dimg.GraphicContext) bool {
    // {some movement code removed for clarity, see the demo code for full function}
    // draws red 🔴 laser
    gc.SetFillColor(color.RGBA{0xff, 0x00, 0x00, 0xff})
    gc.SetStrokeColor(color.RGBA{0xff, 0x00, 0x00, 0xff})

    gc.ArcTo(gs.laserX, gs.laserY, gs.laserSize, gs.laserSize, 0, math.Pi*2)
return true  // Yes, we drew something, copy it over to the browser

If you do want to render outside the animation loop, a simple way to cause the code to draw the frame on schedule, independent from the browsers callbacks, is to use time.Tick. An example is in the demo app below.

If however your image is only updated from user input or some network activity, then it would be straightforward to fire the redraw only when required from these inputs. This can be controlled within the Render function, by just returning FALSE at the start. Nothing is draw, nor copied (saving CPU time) and the previous frames data remains.

Known issues !

There is currently a likely race condition for long draw functions, where the requestAnimationFrame may get a partially completed image buffer. This is more likely the longer the user render operation takes. Currently think how best to handle this, ideally without locks. Turns out this is not an issue, due to the single threaded nature. Eventually if drawing is in a separate thread, this will have to be handled.


A simple demo can be found in: ./demo directory. This is a shameless rewrite of the 'Moving red Laser' demo by Martin Olsansky

Compile with GOOS=js GOARCH=wasm go build -o main.wasm

Includes a Caddy configuration file to support WASM, so will serve by just running 'caddy' in the demo directory and opening browser to http://localhost:8080


Live Demo available at:


This library was written after a weekend of investigation and posted on request for the folks on #webassembly on Gophers Slack.

I intend to extend it further, time permitting, into fully fledged support package for all things go-canvas-wasm related, using this image frame method.

Several of the ideas I'm considering are:

  •  Support for layered canvas, at least 3 for 'background', 'action' and 'user interaction'
  •  Traps & helper functions for mouse interactions over the canvas
  •  Unit tests - soon as I figure out how to do tests for WASM work.
  •  Performance improvements in the image buffer copy - has been suggested as a place to start.
  •  Detect if nothing has changed for the frame, and if so, don't even recopy the buffer, saving yet more time. May be useful for layers that change less frequently.
  •  Multiple draw / render frames to fix the 'incomplete image' problem. -- Not actually a problem
  •  Tidy up the close/end frame functionality to properly release resources on page unload and prevent 'browser reload errors' due to missing animation callback function.
  •  Update for Go 1.13 and Go Modules
  •  Add FPS Calculator metric

Others ? Feedback, suggestions etc. welcome. I can be found on Gophers Slack, #Webassembly channel.

Mark Farnan, February 2020

Author: Markfarnan
Source Code: 
License: Apache-2.0 license

#go #golang #canvas #html5 #wasm 

Go-canvas: Library to Use HTML5 Canvas From Go-WASM

Voxel-engine: 3D HTML5 Voxel Game Engine


A voxel engine in javascript using three.js


var createGame = require('voxel-engine')
var game = createGame()


voxel-engine is an OPEN Open Source Project. This means that:

Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.

See the file for more details.


multiplex is only possible due to the excellent work of the following contributors:

Max OgdenGitHub/maxogdenTwitter/@maxogden



Returns a new game instance. options defaults to:

  texturePath: './textures/',
  generate: function(x,y,z) {
    return x*x+y*y+z*z <= 15*15 ? 1 : 0 // sphere world
  materials: [['grass', 'dirt', 'grass_dirt'], 'brick', 'dirt'],
  materialFlatColor: false,
  chunkSize: 32,
  chunkDistance: 2,
  worldOrigin: [0, 0, 0],
  controls: { discreteFire: false },
  lightsDisabled: false,
  fogDisabled: false,
  generateChunks: true,
  mesher: voxel.meshers.culled,
  playerHeight: 1.62


Player Size

Default 'player size' is a 1/2 block long/wide and 1.5 blocks high:

game.playerAABB().width() // => 12.5
game.playerAABB().height() // => 37.5

See implementation of Game.prototype.playerAABB for more details.


  • block/voxel/cube -> mostly interchangeable. The minecrafty blocks you see on the screen.
  • chunk: is a piece of the world that contains voxels. try to pretend that these don't exist
  • AABB: bounding volume
  • voxeljs: not 100% consistent yet, 'voxel.js' also acceptable, but definitely not 'VoxelJS'.
  • dims: short for 'dimensions'. Perhaps obvious to some.
  • yaw: rotation around the vertical axis.
  • pitch: rotation around a horizontal axis.


  • x, z: horizontal plane
  • y: vertical plane

We try to always use arrays to represent vectors (aka positions)

  • [x, y, z]

Sometimes you may also see objects used, e.g. {x: 0, y: 0, z: 0}, this is because three.js uses objects for vectors.

Generating voxel worlds

Worlds have many chunks and chunks have many voxels. Chunks are cube shaped and are chunkSize x/y/z (default 32/32/32 - 32768 voxels per chunk). When the game starts it takes the worldOrigin and generates chunkDistance chunks in every x/y/z dimension (chunkDistance default of 2 means the game will render 2 chunks behind you, 2 in front etc for a total of 16 chunks.).

There is one major coordinate system in voxel.js: "game coordinates" (aka world coordinates)

  • every object added to a three.js scene gets a x/y/z position in game coordinates. in voxel-engine 1 game coordinate is the width of 1 voxel. when generating the world or interacting with individual voxels you can refer to voxels by coordinates. an example coordinate might be [34, -50, 302] which would mean starting from the worldOrigin 34 voxels over, 50 down and 302 forward

There are also some other less used coordinate systems that you should be aware of:

  • chunk coordinates: logically the same as voxel coordinates but for chunks. you probably won't need to use these as they are just used internally for rendering the world but it is good to know they exist.
  • local object coordinates: when you add items and other things to the game that aren't voxel terrain you introduce a new relative coordinate system inside each thing. so if you add a player 3d model body and you want to put a hat on the body you could position the hat relative to the body coordinates, etc

When you create a game you can also pass functions that the game will ask for voxel data. Here is an example generate function that makes a randomly textured cube world with a diameter of 20 voxels:

function generator(x, y, z) {
  if (x*x + y*y + z*z > 20*20) return 0
  return Math.floor(Math.random() * 4) + 1

The generate function will be called once for each voxel in the world. x, y and z will be values in game coordinates.

Generate a flat world 1 block high

Flat world is a nicer way to start (at least you can't fall off the edge). This places the player just above the ground.

var game = createGame({
  generate: function(x, y, z) {
    return y === 1 ? 1 : 0

Interacting with the voxel world

Get current player position

This returns a THREE.js Vector3 object (which just means an object with 'x', 'y', and 'z').

Toggle a block on/off

game.setBlock(pos, 0) // off
game.setBlock(pos, 1) // on
game.setBlock(pos, 2) // on, with another material

Get the chunk at some world coordinates:


Get the voxel coordinates at some position (relative to that voxels chunk):


Create a brand new voxel at some position.

Intended for use in first player contexts as it checks if a player is standing in the way of the new voxel. If you don't care about that then just use setBlock:

gameInstance.createBlock(pos, val)

val can be 0 or you can also use any single digit integer 0-9. These correspond to the materials array that you pass in to the game.

Set the value of a voxel at some position:

gameInstance.setBlock(pos, val)

Get the value of a voxel at some position:


If you wanna see the lower level API for voxel data manipulation look at chunker.js inside the voxel module.


shoots a ray and collides with voxels

gameInstance.raycastVoxels(start, position, distance)

if you just type gameInstance.raycastVoxels() it will default to using the current main camera position and direction, and default distance of 10, and epsilon of 1e-8

you will get back an object with the precise position, voxel position, direction, face normal and voxel value of the voxel that you intersected, or false if there was no collision

Create a new voxel adjacent to an existing voxel

first do a .raycastVoxels() then do gameInstance.createAdjacent(raycastResults, materialIndex)

Game events

There are a number of events you can listen to once you've instantiated a game. we use the node.js event emitter library which uses the following syntax for subscribing:

emitter.on('eventname', function(arg1, arg2, etc) {})

game.on('mouseup', function(pos) {}), game.on('mousedown', function(pos) {})

Captures mouse activity. pos is the game coordinate of the intersection of the voxel that you clicked on (if any)

game.on('tick', function(delta) {})

emits every time the game renders (usually no more than 60 times a second). delta is the time in milliseconds between this render and the last render

game.on('collision', function(item) {})

Called every tick when an item is colliding with the player. Callback is passed the item that is colliding.

game.voxelRegion.on('change', function(pos) {})

emits when you move between voxels. pos has x, y, and z voxel coordinates of the voxel you just entered

`game.chunkRegion.on('change', function(pos) {})``

emits when you move between chunks. pos has x, y, and z chunk coordinates of the chunk you just entered

game.on('renderChunk', function(chunk) {})

emits when a chunk is drawn (using the showChunk method). chunk is the full chunk object, which has the voxel data and a .position and .dims

game.on('missingChunk', function(chunkPosition) {})

emits when the player moves into range of a chunk that isn't loaded yet. if your game has generateChunks set to true it will automatically create the chunk and render it but if you are providing your own chunk generation then you can use this to hook into the game.

game.on('dirtyChunkUpdate', function(chunk) {})

emits when game updates a chunk, this is usually triggered when a chunk gets edited. if game.setBlock were to get called 50 times on one chunk in between renders, dirtyChunkUpdate will emit once with the chunk that gets updated

game.on('setBlock', function(pos, val, old) {})

emits whenever game.setBlock gets called


Check for collisions between an item and other 'things'

Detects collisions between an item and other items, or voxels.

game.getCollisions(item.mesh.position, item)

This will give you back a 'collisions object' whose keys are positions on the object and values are arrays of the positions of faces that are colliding.

For example, here we have 4 faces colliding with the bottom of our object:

  back: Array[0]
  bottom: Array[4]
  down: Array[1]
  forward: Array[0]
  left: Array[0]
  middle: Array[0]
  right: Array[0]
  top: Array[0]
  up: Array[0]


Loading textures onto the texture atlas.

game.materials.load(['obsidian', 'dirt'], function(textures) { })

Both of these textures will be loaded into the texture atlas and expanded creating 2 voxel block types.

Texture-less worlds with flat colors

You can specify hex colors to use as materials, just pass these options when creating a game:

  materials: ["#fff", "#000", "#ff0000"],
  materialFlatColor: true


  • Items are non-voxel objects you can add to your game. e.g. Monsters/Players, Powerups, etc.
  • Items currently implement their own physics, which is calculated every 'tick' by running an items' item.tick function. It's not very sophisticated.
  • Items .mesh property is the thing that's actually processed by the THREE.js engine. Other properties of item are used in voxel.js to update the mesh, e.g. item.velocity.y is used every tick to calculate the next position the mesh should be in.
  • Using the current item physics system, setting item.resting to false will force an item to recalculate it's position.

Example: Creating an Item

// create a mesh and use the internal game material (texture atlas)
var mesh = new game.THREE.Mesh(
  new game.THREE.CubeGeometry(1, 3, 1), // width, height, depth

// paint the mesh with a specific texture in the atlas
game.materials.paint(mesh, 'obsidian')

// move the item to some location
mesh.position.set(0, 3, -5)

var item = game.addItem({
  mesh: mesh,
  size: 1,
  velocity: { x: 0, y: 0, z: 0 } // initial velocity
// use `game.removeItem(item)` to remove

voxel interchange format

  "voxels": [packed 1D array of voxels],
  "dimensions": [2, 2, 2],
  "position": [10, 10, 10]

this should be generated by something like this:

  var length = 5, width = 5, depth = 5
  var start = [10, 10, 10]
  var voxels = new Int8Array(length * width * depth)
  var idx = 0
  for(var z = start[2]; z < depth; ++z)
  for(var y = start[1]; y < height; ++y)
  for(var x = start[0]; x < length; ++x, ++idx) {
    voxels[idx] = getVoxelDataFor(x+start[0], y+start[1], z+start[2])
  return {voxels: voxels, dimensions: [length, width, height], position: start}


setTimeout and setInterval work fine when timing things against the computer's clock but what about staying in sync with the game's clock? When the game lags, is paused or hasn't begun you probably don't want your timed operations firing.

game.setInterval(fn, duration[, args]) and game.setTimeout(fn, duration[, args]) are available and similar to the built in interval functions but stay in sync with the game's clock.

An example is we want our object to jump every 2 seconds. Normally we'd just do:

setInterval(function() {
}, 2000)

But if the game's frame rate drops or the game hasn't begun the computer will still fire the jump() function every 2 seconds. Thus causing the object to fly way up into the air.

var clearInterval = game.setInterval(function() {
}, 2000)
// later we can stop the interval by calling clearInterval()

Will achieve the same thing although now when the game's frame rate drops the jump() function won't be called repeatedly and the object will jump at the desired frequency.

style guide

basically with a couple of minor changes:

  • no semicolons
  • single line ifs/fors when appropriate for terseness
  • no hard to understand for n00bs 'tricks' unless they are faster

any contributions (pull requests) in any style are welcome, as long as:

  • they are written in javascript
  • they merge cleanly

if you send a pull request and you use, for example, 4 space indents it will not be rejected but please try to follow conventions when you can

Learn more at

hello world template repo:

Author: Maxogden
Source Code: 
License: BSD-3-Clause license

#javascript #html5 #game 

Voxel-engine: 3D HTML5 Voxel Game Engine
Web  Dev

Web Dev


HTML Form Element | How Does an HTML Form Work?

HTML Form – Input Type and Submit Button Example

Forms are one of the most important parts of the web. Without them, there wouldn't be an easy way to collect data, search for resources, or sign up to receive valuable information.

You can embed forms on websites with the HTML form element. Inside the form element, several inputs are nested. These inputs are also known as form controls.

In this tutorial, we will explore the HTML form element, the various input types it takes, and how to create a submit button with which data is submitted.

By the end, you will know how forms work and you'll be able to make them with confidence.

Basic HTML Form Syntax

<form action="" method="POST">
    <!--Input of any type and textareas goes in here-->

HTML Form Input Types

You use the <input> tag to create various form controls in HTML. It is an inline element and takes attributes such as type, name, minlength, maxlength, placeholder, and so on. Each of these has specific values they take.

The placeholder attribute is important as it helps the user understand the purpose of the input field before they type anything in.

There are 20 different input types, and we will look at them one by one.

Type Text

This type of input takes a value of “text”, so it creates a single line of text input.

<input type="text" placeholder="Enter name" />

An input with the type of text looks like the screenshot below:

Type Password

As the name implies, an input with a type of password creates a password. It is automatically invisible to the user, unless it is manipulated by JavaScript.

<input type="password" placeholder="Enter your password" />


Type Email

Any input with the type of email defines a field for entering an email address.

<input type="email" placeholder="Enter your email" />


Type Number

This type of input lets the user insert numbers only.

<input type="number" placeholder="Enter a number" />


Type Radio

Sometimes, users will need to pick one out of numerous options. An input field with its type attributes set to “radio” lets you do this.

 <input type="radio" />


Type Checkbox

So, with an input type of radio, users will be allowed to pick one out of numerous options. What if you want them to pick as many options as possible? That’s what an input with a type attribute set to checkbox does.

<input type="checkbox" />


Type Submit

You use this type to add a submit button to forms. When a user clicks it, it automatically submits the form. It takes a value attribute, which defines the text that appears inside the button.

<input type="submit" value="Enter to Win" />


Type Button

An input with a type set to button creates a button, which can be manipulated by JavaScript's onClick event listener type. It creates a button just like an input type of submit, but with the exception that the value is empty by default, so it has to be specified.

<input type="button" value="Submit" />


Type File

This defines a field for file submission. When a user clicks it, they are prompted to insert the desired file type, which might be an image, PDF, document file, and so on.

<input type="file" />

The result of an input type of file looks like this:


Type Color

This is a fancy input type introduced by HTML5. With it, the user can submit their favourite color for example. Black (#000000) is the default value, but can be overridden by setting the value to a desired color.

Many developers have used it as a trick to get to select different color shades available in RGB, HSL and alphanumeric formats.

<input type="color" />

This is the result of an input type of color:


Type Search

Input with the type of search defines a text field just like an input type of text. But this time it has the sole purpose of searching for info. It is different from type text in that, a cancel button appears once the user starts typing.

<input type="search" />


Type URL

When the type attribute of an input tag is set to URL, it displays a field where users can enter a URL.

<input type="url" />


Type Tel

An input type of tel lets you collect telephone numbers from users.

<input type="tel" />


Type Date

You might have registered on a website where you requested the date of a certain event. The site probably used an input with the type value set to date to acheive this.

<input type="date" />

This is what an input with type date looks like:


Type Datetime-local

This works like the input type date, but it also lets the user pick a date with a particular time.

<input type="datetime-local" />


Type Week

The input type of week lets a user select a specific week.

<input type="week" />


Type Month

The input with the type of month populates months for the user to pick from when clicked.

<input type="month" />



There are times when a user will need to fill in multiple lines of text which wouldn't be suitable in an input type of text (as it specifies a one-line text field).

textarea lets the user do this as it defines multiple lines of text input. It takes its own attributes such as cols – for the number of columns, and rows for the number of rows.

<textarea cols="50" rows="20"></textarea>


Multiple Select Box

This is like a radio button and checkbox in one package. It is embedded in the page with two elements – a select element and an option, which is always nested inside select.

By default, the user can only pick one of the options. But with multiple attributes, you can let the user select more than one of the options.

      <option value="HTML">Select a Language</option>
      <option value="HTML">HTML</option>
      <option value="CSS">CSS</option>
      <option value="JavaScript">JavaScript</option>
      <option value="React">React</option>


How to Label HTML Inputs

Assigning labels to form controls is important. When they're properly connected to the input field through their for attribute and the input’s id attribute, it's easier for the user to use as they can just click the label itself to access the input.

<label for="name">Name</label>
<input type="text" id="name" /> <br />
<label for="check">Agree with terms</label>
<input type="checkbox" id="check" />


How HTML Forms Work

When a user fills in a form and submits it with the submit button, the data in the form controls are sent to the server through GET or POST HTTP request methods.

So how is the server indicated? The form element takes an action attribute, which must have its value specified to the URL of the server. It also takes a method attribute, where the HTTP method it uses to convey the values to the server is specified.

This method could be GET or POST. With the GET method, the values entered by the user are visible in the URL when the data is submitted. But with POST, the values are sent in HTTP headers, so those values are not visible in the URL.

If a method attribute is not used in the form, it is automatically assumed that the user wants to use the GET method, because it’s the default.

So when should you use the GET or POST method? Use the GET method for submitting non-sensitive data or retrieving data from a server (for example, during searches). Use the POST request when submitting files or sensitive data.

Mini Project: Build a Basic Contact Form

Let’s take what we’ve learned about forms and use it to make a simple contact form. I will also introduce a few new concepts as we go to round it all out.

Here's the HTML:

        <legend>Contact me</legend>
        <div class="form-control">
          <label for="name">Name</label>
          <input type="name" id="name" placeholder="Enter your name" required />

        <div class="form-control">
          <label for="email">Email</label>
            placeholder="Enter your email"

        <div class="form-control">
          <label for="message">Message</label>
            placeholder="Enter your message"
        <input type="submit" value="Send" class="submit-btn" />

What’s going on in this HTML code?

First, a form element is wrapping every other element. It has an action set to “”, a dummy server where the form data will be received.

After the form element, every other element is also surrounded by a fieldset element with a legend tag right under it.

We use the fieldset element to group related inputs together, and the legend tag contains a caption conveying what the form is about.

The inputs name, email, and textarea are all in a div with a class of form-control. So they behave like a block element, in order to make styling easier with CSS.

They are also validated with the required attribute, so the form fails to submit when those fields are empty or when the user fails to type in the values in the appropriate format.

After all that, we'll have the result in the screenshot below:

How ugly is that? We need to apply some styling!

Here's the CSS:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    font-family: cursive;

    textarea {
    width: 100%;
    padding: 5px;
    outline: none;

  label {
    line-height: 1.9rem;

  input[type="submit"] {
   transform: translate(2.2%);
   padding: 3px;
   margin-top: 0.6rem;
   font-family: cursive;
   font-weight: bold;

 fieldset {
   padding: 20px 40px;

What’s the CSS code doing here?

We center everything in the body horizontally with Flexbox, and vertically with a 100% viewport height. We used a font-family of cursive.

We gave the inputs and textarea a width of 100% so they go all the way across. The labels got a minimal line-height of 1.9rem (30.4px), so they don’t stay too close to their respective inputs.

We specifically styled the button (input type button) with the transform property to push it to the center as it was off center a bit. We gave it a padding of 3px for more spacing around it. We then selected a cursive font-family for it with a weight of bold.

Because the button was too close to the textarea, we set a margin-top of 0.6rem to push it down a little bit.

We gave our fieldset element a padding of 20px at the top and bottom, with 40px at the left and right to push apart the border it creates around the form elements it is wrapped in.

At the end of it all, we have the beautiful form below:


I hope this tutorial has helped you understand how forms work. Now you should have the knowledge you need to integrate forms into your websites so you can start collecting data.

Thank you for reading, and keep coding.

Original article source at

#html #html5 #programming #developer #webdev 

HTML Form Element | How Does an HTML Form Work?
Duane  Purdy

Duane Purdy


Gumbo Parser: An HTML5 Parsing Library in Pure C99

Gumbo - A pure-C HTML5 parser.

Gumbo is an implementation of the HTML5 parsing algorithm implemented as a pure C99 library with no outside dependencies. It's designed to serve as a building block for other tools and libraries such as linters, validators, templating languages, and refactoring and analysis tools.

Goals & features:

  • Fully conformant with the HTML5 spec.
  • Robust and resilient to bad input.
  • Simple API that can be easily wrapped by other languages.
  • Support for source locations and pointers back to the original text.
  • Support for fragment parsing.
  • Relatively lightweight, with no outside dependencies.
  • Passes all html5lib tests, including the template tag.
  • Tested on over 2.5 billion pages from Google's index.


  • Execution speed. Gumbo gains some of this by virtue of being written in C, but it is not an important consideration for the intended use-case, and was not a major design factor.
  • Support for encodings other than UTF-8. For the most part, client code can convert the input stream to UTF-8 text using another library before processing.
  • Mutability. Gumbo is intentionally designed to turn an HTML document into a parse tree, and free that parse tree all at once. It's not designed to persistently store nodes or subtrees outside of the parse tree, or to perform arbitrary DOM mutations within your program. If you need this functionality, we recommend translating the Gumbo parse tree into a mutable DOM representation more suited for the particular needs of your program before operating on it.
  • C89 support. Most major compilers support C99 by now; the major exception (Microsoft Visual Studio) should be able to compile this in C++ mode with relatively few changes. (Bug reports welcome.)
  • Security. Gumbo was initially designed for a product that worked with trusted input files only. We're working to harden this and make sure that it behaves as expected even on malicious input, but for now, Gumbo should only be run on trusted input or within a sandbox. Gumbo underwent a number of security fixes and passed Google's security review as of version 0.9.1.

Wishlist (aka "We couldn't get these into the original release, but are hoping to add them soon"):

  • Full-featured error reporting.
  • Additional performance improvements.
  • DOM wrapper library/libraries (possibly within other language bindings)
  • Query libraries, to extract information from parse trees using CSS or XPATH.


To build and install the library, issue the standard UNIX incantation from the root of the distribution:

$ ./
$ ./configure
$ make
$ sudo make install

Gumbo comes with full pkg-config support, so you can use the pkg-config to print the flags needed to link your program against it:

$ pkg-config --cflags gumbo         # print compiler flags
$ pkg-config --libs gumbo           # print linker flags
$ pkg-config --cflags --libs gumbo  # print both

For example:

$ gcc my_program.c `pkg-config --cflags --libs gumbo`

See the pkg-config man page for more info.

There are a number of sample programs in the examples/ directory. They're built automatically by 'make', but can also be made individually with make <programname> (eg. make clean_text).

To run the unit tests, you'll need to have googletest downloaded and unzipped. The googletest maintainers recommend against using make install; instead, symlink the root googletest directory to 'gtest' inside gumbo's root directory, and then make check:

$ unzip
$ cd gumbo-*
$ ln -s ../gtest-1.6.0 gtest
$ make check

Gumbo's make check has code to automatically configure & build gtest and then link in the library.

Debian and Fedora users can install libgtest with:

$ apt-get install libgtest-dev  # Debian/Ubuntu
$ yum install gtest-devel       # CentOS/Fedora

Note for Ubuntu users: libgtest-dev package only install source files. You have to make libraries yourself using cmake:

$ sudo apt-get install cmake
$ cd /usr/src/gtest
$ sudo cmake CMakeLists.txt
$ sudo make
$ sudo cp *.a /usr/lib

The configure script will detect the presence of the library and use that instead.

Note that you need to have super user privileges to execute these commands. On most distros, you can prefix the commands above with sudo to execute them as the super user.

Debian installs usually don't have sudo installed (Ubuntu however does.) Switch users first with su -, then run apt-get.

Basic Usage

Within your program, you need to include "gumbo.h" and then issue a call to gumbo_parse:

#include "gumbo.h"

int main() {
  GumboOutput* output = gumbo_parse("<h1>Hello, World!</h1>");
  // Do stuff with output->root
  gumbo_destroy_output(&kGumboDefaultOptions, output);

See the API documentation and sample programs for more details.

A note on API/ABI compatibility

We'll make a best effort to preserve API compatibility between releases. The initial release is a 0.9 (beta) release to solicit comments from early adopters, but if no major problems are found with the API, a 1.0 release will follow shortly, and the API of that should be considered stable. If changes are necessary, we follow semantic versioning.

We make no such guarantees about the ABI, and it's very likely that subsequent versions may require a recompile of client code. For this reason, we recommend NOT using Gumbo data structures throughout a program, and instead limiting them to a translation layer that picks out whatever data is needed from the parse tree and then converts that to persistent data structures more appropriate for the application. The API is structured to encourage this use, with a single delete function for the whole parse tree, and is not designed with mutation in mind.

Python usage

To install the python bindings, make sure that the C library is installed first, and then sudo python install from the root of the distro. This installs a 'gumbo' module; pydoc gumbo should tell you about it.

Recommended best-practice for Python usage is to use one of the adapters to an existing API (personally, I prefer BeautifulSoup) and write your program in terms of those. The raw CTypes bindings should be considered building blocks for higher-level libraries and rarely referenced directly.

External Bindings and other wrappers

The following language bindings or other tools/wrappers are maintained by various contributors in other repositories:

Author: google
Source Code:
License: Apache-2.0 license

#html5 #html 

Gumbo Parser: An HTML5 Parsing Library in Pure C99
Ruth  Clarke

Ruth Clarke


Chart.js: Simple HTML5 Charts using The Canvas Tag.

Simple yet flexible JavaScript charting for designers & developers


All the links point to the new version 3 of the lib.

In case you are looking for the docs of version 2, you will have to specify the specific version in the url like this:


Instructions on building and testing Chart.js can be found in the documentation. Before submitting an issue or a pull request, please take a moment to look over the contributing guidelines first. For support, please post questions on Stack Overflow with the chartjs tag.

Author: chartjs
Source Code:
License: MIT license

#react-native #react #html5 

Chart.js: Simple HTML5 Charts using The Canvas Tag.
Veronica  Roob

Veronica Roob


HTML5 PHP: An HTML5 Parser and Serializer for PHP


HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has well over five million downloads.

HTML5 provides the following features.

  • An HTML5 serializer
  • Support for PHP namespaces
  • Composer support
  • Event-based (SAX-like) parser
  • A DOM tree builder
  • Interoperability with QueryPath
  • Runs on PHP 5.3.0 or newer


Install HTML5-PHP using composer.

By adding the masterminds/html5 dependency to your composer.json file:

  "require" : {
    "masterminds/html5": "^2.0"

By invoking require command via composer executable:

composer require masterminds/html5

Basic Usage

HTML5-PHP has a high-level API and a low-level API.

Here is how you use the high-level HTML5 library API:

// Assuming you installed from Composer:
require "vendor/autoload.php";

use Masterminds\HTML5;

// An example HTML document:
$html = <<< 'HERE'
  <body id='foo'>
    <h1>Hello World</h1>
    <p>This is a test of the HTML5 parser.</p>

// Parse the document. $dom is a DOMDocument.
$html5 = new HTML5();
$dom = $html5->loadHTML($html);

// Render it as HTML5:
print $html5->saveHTML($dom);

// Or save it to a file:
$html5->save($dom, 'out.html');

The $dom created by the parser is a full DOMDocument object. And the save() and saveHTML() methods will take any DOMDocument.


It is possible to pass in an array of configuration options when loading an HTML5 document.

// An associative array of options
$options = array(
  'option_name' => 'option_value',

// Provide the options to the constructor
$html5 = new HTML5($options);

$dom = $html5->loadHTML($html);

The following options are supported:

  • encode_entities (boolean): Indicates that the serializer should aggressively encode characters as entities. Without this, it only encodes the bare minimum.
  • disable_html_ns (boolean): Prevents the parser from automatically assigning the HTML5 namespace to the DOM document. This is for non-namespace aware DOM tools.
  • target_document (\DOMDocument): A DOM document that will be used as the destination for the parsed nodes.
  • implicit_namespaces (array): An assoc array of namespaces that should be used by the parser. Name is tag prefix, value is NS URI.

The Low-Level API

This library provides the following low-level APIs that you can use to create more customized HTML5 tools:

  • A SAX-like event-based parser that you can hook into for special kinds of parsing.
  • A flexible error-reporting mechanism that can be tuned to document syntax checking.
  • A DOM implementation that uses PHP's built-in DOM library.

The unit tests exercise each piece of the API, and every public function is well-documented.

Parser Design

The parser is designed as follows:

  • The Scanner handles scanning on behalf of the parser.
  • The Tokenizer requests data off of the scanner, parses it, clasifies it, and sends it to an EventHandler. It is a recursive descent parser.
  • The EventHandler receives notifications and data for each specific semantic event that occurs during tokenization.
  • The DOMBuilder is an EventHandler that listens for tokenizing events and builds a document tree (DOMDocument) based on the events.

Serializer Design

The serializer takes a data structure (the DOMDocument) and transforms it into a character representation -- an HTML5 document.

The serializer is broken into three parts:

  • The OutputRules contain the rules to turn DOM elements into strings. The rules are an implementation of the interface RulesInterface allowing for different rule sets to be used.
  • The Traverser, which is a special-purpose tree walker. It visits each node node in the tree and uses the OutputRules to transform the node into a string.
  • HTML5 manages the Traverser and stores the resultant data in the correct place.

The serializer (save(), saveHTML()) follows the section 8.9 of the HTML 5.0 spec. So tags are serialized according to these rules:

  • A tag with children: <foo>CHILDREN</foo>
  • A tag that cannot have content: <foo> (no closing tag)
  • A tag that could have content, but doesn't: <foo></foo>

Known Issues (Or, Things We Designed Against the Spec)

Please check the issue queue for a full list, but the following are issues known issues that are not presently on the roadmap:

  • Namespaces: HTML5 only supports a selected list of namespaces and they do not operate in the same way as XML namespaces. A : has no special meaning. By default the parser does not support XML style namespaces via :; to enable the XML namespaces see the XML Namespaces section
  • Scripts: This parser does not contain a JavaScript or a CSS interpreter. While one may be supplied, not all features will be supported.
  • Rentrance: The current parser is not re-entrant. (Thus you can't pause the parser to modify the HTML string mid-parse.)
  • Validation: The current tree builder is not a validating parser. While it will correct some HTML, it does not check that the HTML conforms to the standard. (Should you wish, you can build a validating parser by extending DOMTree or building your own EventHandler implementation.)
    • There is limited support for insertion modes.
    • Some autocorrection is done automatically.
    • Per the spec, many legacy tags are admitted and correctly handled, even though they are technically not part of HTML5.
  • Attribute names and values: Due to the implementation details of the PHP implementation of DOM, attribute names that do not follow the XML 1.0 standard are not inserted into the DOM. (Effectively, they are ignored.) If you've got a clever fix for this, jump in!
  • Processor Instructions: The HTML5 spec does not allow processor instructions. We do. Since this is a server-side library, we think this is useful. And that means, dear reader, that in some cases you can parse the HTML from a mixed PHP/HTML document. This, however, is an incidental feature, not a core feature.
  • HTML manifests: Unsupported.
  • PLAINTEXT: Unsupported.
  • Adoption Agency Algorithm: Not yet implemented. (

XML Namespaces

To use XML style namespaces you have to configure well the main HTML5 instance.

use Masterminds\HTML5;
$html = new HTML5(array(
    "xmlNamespaces" => true

$dom = $html->loadHTML('<t:tag xmlns:t=""/>');

$dom->documentElement->namespaceURI; //

You can also add some default prefixes that will not require the namespace declaration, but its elements will be namespaced.

use Masterminds\HTML5;
$html = new HTML5(array(

$dom = $html->loadHTML('<t:tag/>');

$dom->documentElement->namespaceURI; //

Thanks to...

The dedicated (and patient) contributors of patches small and large, who have already made this library better.See the CREDITS file for a list of contributors.

We owe a huge debt of gratitude to the original authors of html5lib.

While not much of the original parser remains, we learned a lot from reading the html5lib library. And some pieces remain here. In particular, much of the UTF-8 and Unicode handling is derived from the html5lib project.


This software is released under the MIT license. The original html5lib library was also released under the MIT license.


Certain files contain copyright assertions by specific individuals involved with html5lib. Those have been retained where appropriate.

Author: Masterminds
Source Code:
License: View license

#php #html5 

HTML5 PHP: An HTML5 Parser and Serializer for PHP
宇野  和也

宇野 和也





● 目次
Chapter 1 Canvasを用意 01:12
Chapter 2 道のデコボコを作る 04:07
Chapter 3  アニメーションさせる 11:52
Chapter 4 プレイヤーを描画 12:40
Chapter 5 プレイヤーを動かす 16:28
Chapter 6  プレイヤーの角度を変更 21:55
Chapter 7 矢印キーで操作 25:26
Chapter 8 ゲームオーバーを管理 30:17
Chapter 9 トランプの画像に変更 32:57






#programming #javascript  #html5 

Arden  Keebler

Arden Keebler


Build Particle System of Bouncing Balls using HTML5 & JS (P2)

In this video tutorial, We'll show you How to Build Particle System of Bouncing Balls using HTML5 Canvas and Javascript (P2).

#javascript #html5 #html 

Build Particle System of Bouncing Balls using HTML5 & JS (P2)

Html5lib: A Pure-Python Library for Parsing HTML


html5lib is a pure-python library for parsing HTML. It is designed to conform to the WHATWG HTML specification, as is implemented by all major web browsers.


Simple usage follows this pattern:

import html5lib
with open("mydocument.html", "rb") as f:
    document = html5lib.parse(f)


import html5lib
document = html5lib.parse("<p>Hello World!")

By default, the document will be an xml.etree element instance. Whenever possible, html5lib chooses the accelerated ElementTree implementation (i.e. xml.etree.cElementTree on Python 2.x).

Two other tree types are supported: xml.dom.minidom and lxml.etree. To use an alternative format, specify the name of a treebuilder:

import html5lib
with open("mydocument.html", "rb") as f:
    lxml_etree_document = html5lib.parse(f, treebuilder="lxml")

When using with urllib2 (Python 2), the charset from HTTP should be pass into html5lib as follows:

from contextlib import closing
from urllib2 import urlopen
import html5lib

with closing(urlopen("")) as f:
    document = html5lib.parse(f,"charset"))

When using with urllib.request (Python 3), the charset from HTTP should be pass into html5lib as follows:

from urllib.request import urlopen
import html5lib

with urlopen("") as f:
    document = html5lib.parse(f,

To have more control over the parser, create a parser object explicitly. For instance, to make the parser raise exceptions on parse errors, use:

import html5lib
with open("mydocument.html", "rb") as f:
    parser = html5lib.HTMLParser(strict=True)
    document = parser.parse(f)

When you're instantiating parser objects explicitly, pass a treebuilder class as the tree keyword argument to use an alternative document format:

import html5lib
parser = html5lib.HTMLParser(tree=html5lib.getTreeBuilder("dom"))
minidom_document = parser.parse("<p>Hello World!")

More documentation is available at


html5lib works on CPython 2.7+, CPython 3.5+ and PyPy. To install:

$ pip install html5lib

The goal is to support a (non-strict) superset of the versions that pip supports.

Optional Dependencies

The following third-party libraries may be used for additional functionality:

  • lxml is supported as a tree format (for both building and walking) under CPython (but not PyPy where it is known to cause segfaults);
  • genshi has a treewalker (but not builder); and
  • chardet can be used as a fallback when character encoding cannot be determined.


Please report any bugs on the issue tracker.


Unit tests require the pytest and mock libraries and can be run using the py.test command in the root directory.

Test data are contained in a separate html5lib-tests repository and included as a submodule, thus for git checkouts they must be initialized:

$ git submodule init
$ git submodule update

If you have all compatible Python implementations available on your system, you can run tests on all of them using the tox utility, which can be found on PyPI.


There's a mailing list available for support on Google Groups, html5lib-discuss, though you may get a quicker response asking on IRC in #whatwg on

Author: html5lib
Source Code:
License: MIT License

#python #html #html5 

Html5lib: A Pure-Python Library for Parsing HTML
Joseph  Norton

Joseph Norton


MelonJS: a Fresh & Lightweight JavaScript/HTML5 Game Engine

melonJS 2

A fresh, modern & lightweight HTML5 game engine

melonJS 2 is a modern version of the melonJS game engine. It has been rebuilt almost entirely using ES6 class, inheritance and semantic, and is bundled using Rollup to provide modern features such as transpiling and tree-shaking.

Note: migrating an existing project to melonJS 2 (version 10.0 and higher) will definitely break your game (ES6 semantic, no more Jay inheritance, nodeJS event emitter, and no backward compatibility with deprecated legacy APIs), and you might want to read first this small step by step guide on upgrading to melonJS 2. If you are looking at the legacy version (9.x and lower) of melonJS, you can find it here under the legacy branch.

melonJS is open-source, licensed under the MIT License, and actively developed and maintained with the help of a small team of enthusiasts at AltByte in Singapore.

About melonJS

melonJS is a fully featured game engine :


  • Standalone library (does not rely on anything else, except a HTML5 capable browser)
  • Compatible with all major browsers (Chrome, Safari, Firefox, Opera, Edge) and mobile devices


  • 2D sprite-based graphic engine
  • Fast WebGL 1 & 2 renderer for desktop and mobile devices with fallback to Canvas rendering
  • High DPI resolution & Canvas advanced auto scaling
  • Sprite with 9-slice scaling option, and animation management
  • built-in effects such as tinting and masking
  • Standard spritesheet, single and multiple Packed Textures support
  • System & Bitmap Text


  • Web Audio support with spatial audio or stereo panning based on Howler
  • fallback to Multi-channel HTML5 audio for legacy browsers


  • Polygon (SAT) based collision algorithm for accurate detection and response
  • Fast Broad-phase collision detection using spatial partitioning
  • Collision filtering for optimized automatic collision detection


  • Mouse and Touch device support (with mouse emulation)
  • Device motion & accelerometer support

Level Editor

  • Tiled map format version +1.0 integration for easy level design
    • Uncompressed Plain, Base64, CSV and JSON encoded XML tilemap loading
    • Orthogonal, Isometric and Hexagonal maps (both normal and staggered)
    • Multiple layers (multiple background/foreground, collision and Image layers)
    • Animated and multiple Tileset support
    • Tileset transparency settings
    • Layers alpha and tinting settings
    • Rectangle, Ellipse, Polygon and Polyline objects support
    • Tiled Objects
    • Flipped & rotated Tiles
    • Dynamic Layer and Object/Group ordering
    • Dynamic Entity loading
    • Shape based Tile collision support


  • Asynchronous asset loading
  • A fully customizable preloader

And Also

  • A state manager (to easily manage loading, menu, options, in-game state)
  • Tween Effects, Transition effects
  • Pooling support for object recycling
  • Basic Particle System
  • nodeJS EventEmitter based event system

Tools integration

Free Texture Packer TexturePacker PhysicsEditor ShoeBox Tiled Cordova

Tools integration and usage with melonJS is documented in our Wiki.

Using melonJS

Basic Hello World Example

import * as me from "";

me.device.onReady(function () {
    // initialize the display canvas once the device/browser is ready
    if (!, 562, {parent : "screen", scale : "auto"})) {
        alert("Your browser does not support HTML5 canvas.");

    // add a gray background to the default Stage me.ColorLayer("background", "#202020"));

    // add a font text display object me.Text(609, 281, {
        font: "Arial",
        size: 160,
        fillStyle: "#FFFFFF",
        textBaseline : "middle",
        textAlign : "center",
        text : "Hello World !"

Simple hello world using melonJS 9.x or higher

Documentation :

For your first time using melonJS, follow these tutorials :

You may find it useful to skim the overview found at the wiki Details & Usage

When starting your own projects, checkout our es6 boilerplate


A few demos of melonJS capabilities :

More examples are available here

Download melonJS

The latest builds with corresponding release note are available for direct download here.

Since version 10.0.0 melonJS provides different build options :

melonjs.module.jsthe ES6 Module (ESM) Bundle
melonjs.module.d.tstypescript declaration file for the ES6 Module (ESM) Bundle
melonjs.jsa ES5 UMD Bundle (directly transpiled from the ES6 version)
melonjs.min.jsa minified version of the ES5 UMD bundle

Alternatively, the latest version of melonJS can be installed through NPM :

$ npm install melonjs

If you need to import the ES6 module of melonjs (e.g. for Webpack):

$ import * as me from 'melonjs/dist/melonjs.module.js';

Or can simply be added to your html, using jsDeliver content delivery network (CDN) :

<!-- load the ES6 module bundle of melonJS v10.0 -->
<script src=""></script>
<!-- omit the version completely to get the latest one -->
<!-- you should NOT use this in production -->
<script src=""></script>

Note: starting from the 10.0.0 version, the debug plugin is no longer provided as part of the melonJS library release, and has been moved to the official boilerplate

Building melonJS

For most users, all you probably want is to use melonJS, and all you need then is just to download the latest built release to get started. The only time you should need to build melonJS is if you want to contribute to the project and start developing on it.

To build your own version of melonJS you will need to install :

  • The Node.js JavaScript runtime and the NPM package manager

Once Node.js and NPM have been installed, you need to install build dependencies, by executing the following in the folder where you cloned the repository :

$ [sudo] npm install

Then build the melonJS source by running:

$ npm run build

The generated library will be available under the build directory :

  • melonjs.js : plain ES5 UMD bundle
  • melonjs.min.js : minified ES5 UMD bundle
  • melonjs.module.js : plain ES6 module

To run the melonJS test suite simply use the following:

$ npm run test

This will run the jasmine spec tests with the output displayed on the shell. Do note that the latest Chrome version is required, as the test unit will run the Browser in a headless mode (in case of failed tests, upgrade your browser).

Building the documentation

Similarly, you can build your own copy of the docs locally by running :

$ npm run doc

The generated documentation will be available in the docs directory

WIP Builds

melonJS uses Travis-CI for automated testing and build uploads. The latest build artifacts can be downloaded from the melonjs-builds bucket.

Questions, need help ?

If you need technical support, you can contact us through the following channels :

  • Forums: with melonJS 2 we moved to a new discourse forum, but we can still also find the previous one here
  • Chat: come and chat with us on discord, or gitter
  • we tried to keep our wikipage up-to-date with useful links, tutorials, and anything related melonJS.

Download Details: 
Author: melonjs
Source Code: 
License: MIT
#javascript #gamedev #webgl #html5 #gameengine #gamedevelopment #melonjs #html5 #web3 #webgl2 

MelonJS: a Fresh & Lightweight JavaScript/HTML5 Game Engine
Archie  Clayton

Archie Clayton


Phaser - HTML5 Game Framework

Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development.

Along with the fantastic open source community, Phaser is actively developed and maintained by Photon Storm. As a result of rapid support, and a developer friendly API, Phaser is currently one of the most starred game frameworks on GitHub.

Thousands of developers from indie and multi-national digital agencies, and universities worldwide use Phaser. Take a look at their incredible games.

After 13 beta releases, over 200 resolved issues, thousands of lines of new code and the culmination of over 6 months incredibly hard work, Phaser 3.50 was finally released in December 2020 and we're continuing with updates into 2021 with this new 3.55 release. 3.55 focuses mostly on fixing issues, but also addresses a performance issue with mixing Sprites and Graphics objects together.

It's not hyperbole or exaggeration when I say that Phaser 3.50 is the single biggest point release ever in the history of Phaser. There are quite literally hundreds of new features to explore, updates to key areas and of course bug fixes. I did actually try counting all the changes, but gave up after I'd reached 900 of them! Thankfully, they are, as always, meticulously detailed in the Change Log. The changes for 3.50 actually grew so large that I had to split them out from the main Change Log and put them into their own file.

However, don't let this overwhelm you. A massive number of the changes are purely internal and while there are absolutely some API breaking changes in this release (hence the large version number jump), we've kept them as sensible as possible. We already know of lots of devs who have upgraded with minimal, or no, changes to their actual game code. We cannot guarantee that for everyone, of course, but depending on how complex your game is, the chances are good.

There is plenty to be excited about in this version. It pulls together most of the R&D that took place earlier this year for Phaser 4 and delivers it to you in version 3. New features include full support for post-processing effects via the new Post FX Pipeline, multi-texture support for faster WebGL rendering, a brand new Layer Game Object for the ability to group and post process objects without impacting their transforms, new event hooks, a massive overhaul of the Animation system, funky looking new Point Lights, a new Pipeline Manager, new Camera effects, the latest version of the Spine Plugin, an extremely powerful new Mesh Game Object, a brand new Render Texture, huge improvements to Bitmap Text, isometric and hexagonal Tilemap support, a new Pushable Arcade Physics Body type, new Geometry Intersection tests, Light 2D Updates and lots, lots, lots more!

As usual, I'd like to send my thanks to the Phaser community for their help in both reporting issues and submitting pull requests to fix them. So, please do spend some time digging through the Change Log. I assure you, it's worth while :)

I'd like to send a massive thank-you to everyone who supports Phaser on Patreon, GitHub Sponsors and our corporate backers. Your continued funding allows me to keep working on Phaser full-time and this monster of a new release is the very real result of that. If you've ever considered becoming a backer, now is the perfect time!

If you'd like to stay abreast of developments then I'm now publishing them to the Phaser Patreon. Here you can find the latest development reports including the concepts behind Phaser 4.

You can also follow Phaser on Twitter and chat with fellow Phaser devs in our Discord.

Phaser 3 wouldn't have been possible without the fantastic support of the community and Patreon. Thank you to everyone who supports our work, who shares our belief in the future of HTML5 gaming, and Phaser's role in that.

Happy coding everyone!


Rich - @photonstorm

Because Phaser is an open source project, we cannot charge for it in the same way as traditional retail software. What's more, we don't ever want to. After all, it's built on, and was born from, open web standards. It's part of our manifesto that the core framework will always be free, even if you use it commercially, as many of you do.

You may not realize it, but because of this, we rely 100% on community backing to fund development.

Those funds allow Phaser to improve, and when it improves, everyone involved benefits. Your support helps secure a constant cycle of updates, fixes, new features and planning for the future.

There are other benefits to backing Phaser, too:

Backers Perks

We use Patreon to manage the backing and you can support Phaser from $1 per month. The amount you pledge is entirely up to you and can be changed as often as you like. Patreon renews monthly, just like Netflix. You can, of course, cancel at any point. Tears will be shed on this end, but that's not your concern.

You can also support us by using crypto currencies. The Phaser wallet addresses are:

  • Ethereum: 0x10412d654b44570950631aA0C3E3f3aFcAEfAB4C
  • Bitcoin: 3MjS5iNH8yUBfYW2emxBk7rRUkP6ncrkXC

Extra special thanks to the following companies whose support makes Phaser possible:

Phaser 3 is available via GitHub, npm and CDNs:


Install via npm:

npm install phaser


Phaser is on jsDelivr which is a "super-fast CDN for developers". Include the following in your html:

<script src="//"></script>

or the minified version:

<script src="//"></script>

API Documentation

Go to to read the docs online using our brand new interface. Use the links to navigate the namespaces, classes and Game Objects lists and also use the new search box.

The documentation for Phaser 3 is an on-going project. Please help us by contributing improved docs and examples.

TypeScript Definitions

The TypeScript definitions can be found inside the types folder. They are also referenced in the types entry in package.json.

Depending on your project, you may need to add the following to your tsconfig.json file:

"typeRoots": [
"types": [

We recently published a new Phaser 3 TypeScript Project Template, which you can use to get started with if you like.

The TS defs are automatically generated from the JSDoc comments found in the Phaser source code. If you wish to help refine them then you must edit the Phaser JSDoc blocks directly, not the defs file. You can find more details about the parser we built in the scripts/tsgen folder.


We use Webpack to build Phaser and we take advantage of its conditional build flag feature to handle renderer swapping. If you wish to use Webpack with Phaser then please use our Phaser 3 Project Template as it's already set-up to handle the build conditions Phaser needs. Recent changes to our build steps mean you should now be able to use any other packager, like Parcel, without any config changes.

Tutorials and guides on Phaser 3 development are being published every week.

We've 3 tutorials related specifically to creating Facebook Instant Games with Phaser:

Source Code Examples

During our development of Phaser 3, we created hundreds of examples with the full source code and assets ready available. These examples are now fully integrated into the Phaser website. You can also browse them on Phaser 3 Labs via a more advanced interface, or clone the examples repo. We are constantly adding to and refining these examples.

Huge list of Phaser 3 Plugins

Super community member RexRainbow has been publishing Phaser 3 content for years, building up an impressive catalogue in that time. You'll find loads of plugins, from UI controls such as text input boxes, to Firebase support, Finite State Machines and lots more. As well as the plugins there is also a comprehensive set of 'Notes' about Phaser 3, going into great detail about how the various systems work. It's an invaluable resource and well worth checking out at

Create Your First Phaser 3 Example

Create an index.html page locally and paste the following code into it:

<!DOCTYPE html>
    <script src=""></script> 



This is a standard empty webpage. You'll notice there's a script tag that is pulling in a build of Phaser 3, but otherwise this webpage doesn't do anything yet. Now let's set-up the game config. Paste the following between the <script></script> tags:

var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 }
    scene: {
        preload: preload,
        create: create

config is a pretty standard Phaser 3 Game Configuration object. We tell config to use the WebGL renderer if it can, set the canvas to a size of 800x600 pixels, enable Arcade Physics, and finally call the preload and create functions. preload and create have not been implemented yet, so if you run this JavaScript code, you will have an error. Add the following after config:

var game = new Phaser.Game(config);

function preload ()

    this.load.image('sky', 'assets/skies/space3.png');
    this.load.image('logo', 'assets/sprites/phaser3-logo.png');
    this.load.image('red', 'assets/particles/red.png');

function create ()

game is a Phaser Game instance that uses our configuration object config. We also add function definitions for preload and create. The preload function helps you easily load assets into your game. In preload, we set the Base URL to be the Phaser server and load 3 PNG files.

The create function is empty, so it's time to fill it in:

function create ()
    this.add.image(400, 300, 'sky');

    var particles = this.add.particles('red');

    var emitter = particles.createEmitter({
        speed: 100,
        scale: { start: 1, end: 0 },
        blendMode: 'ADD'

    var logo = this.physics.add.image(400, 100, 'logo');

    logo.setVelocity(100, 200);
    logo.setBounce(1, 1);


Here we add a sky image into the game and create a Particle Emitter. The scale value means that the particles will initially be large and will shrink to nothing as their lifespan progresses.

After creating the emitter, we add a logo image called logo. Since logo is a Physics Image, logo is given a physics body by default. We set some properties for logo: velocity, bounce (or restitution), and collision with the world bounds. These properties will make our logo bounce around the screen. Finally, we tell the particle emitter to follow the logo - so as the logo moves, the particles will flow from it.

Run it in your browser and you'll see the following:

Phaser 3 Demo

(Got an error? Here's the full code)

This is a tiny example, and there are hundreds more for you to explore, but hopefully it shows how expressive and quick Phaser is to use. With just a few easily readable lines of code, we've got something pretty impressive up on screen!


Ourcade have published two great Phaser 3 books. They'll take you from getting set-up, through to finishing your first game using modern JavaScript or TypeScript and they're both completely free! They also publish a huge range of quality tutorials and videos, so be sure to check out their site every week.

HTML5 Cross Platform Game Development with Phaser 3

Learn the secrets of HTML5 game development with Phaser 3.50 while building a cross platform endless runner game. Designed both for beginners and skilled programmers, the course guides you from an empty folder introducing the bare bones of JavaScript to advanced Phaser 3 features. Find out more details about HTML5 Cross Platform Game Development with Phaser.

Building Phaser

There are both plain and minified compiled versions of Phaser in the dist folder of the repository. The plain version is for use during development, and the minified version is for production use. You can and should also create your own builds.

Custom Builds

Phaser 3 is built using Webpack and we take advantage of the Webpack definePlugin feature to allow for conditional building of the Canvas and WebGL renderers and extra plugins. You can custom the build process to only include the features you require. Doing so can cut the main build file size down to just 70KB.

Read our comprehensive guide on creating Custom Builds of Phaser 3 for full details.

Building from Source

If you wish to build Phaser 3 from source, ensure you have the required packages by cloning the repository and then running npm install on your source directory.

You can then run webpack to create a development build in the build folder which includes source maps for local testing. You can also npm run dist to create a minified packaged build in the dist folder. For a list of all commands available use npm run help.

Change Log

Change Log

Due to the increasing size of our Change Logs we have now split them up into three parts:

We've organized the Change Logs into commonly themed sections to make it more digestible, but we appreciate there is a lot in there. Please don't feel overwhelmed! If you need clarification about something, join us on the Phaser Discord and feel free to ask.


The Contributors Guide contains full details on how to help with Phaser development. The main points are:

Found a bug? Report it on GitHub Issues and include a code sample. Please state which version of Phaser you are using! This is vitally important.

Before submitting a Pull Request run your code through ES Lint using our config and respect our Editor Config.

Before contributing read the code of conduct.

Written something cool in Phaser? Please tell us about it in the forum, or email

Created by

Phaser is a Photon Storm production.


Created by Richard Davey. Powered by coffee, anime, pixels and love.

The Phaser logo and characters are © 2021 Photon Storm Limited.

All rights reserved.

"Above all, video games are meant to be just one thing: fun. Fun for everyone." - Satoru Iwata

Visit: The Phaser website and follow on Phaser Twitter
Play: Some of the amazing games #madewithphaser
Learn: API Docs, Support Forum and StackOverflow
Code: 1770+ Examples (source available in this repo)
Read: The Phaser World Newsletter
Discord: Join us on Discord
Extend: With Phaser Plugins
Be awesome: Support the future of Phaser

Download Details: 
Author: photonstorm
Source Code: 
License: MIT
#javascript #gamedev #webgl #canvas #phaser #gamedevelopment #phaserjs #html5

Phaser - HTML5 Game Framework
Jade Bird

Jade Bird


pixijs: The HTML5 Creation Engine

The aim of this project is to provide a fast lightweight 2D library that works across all devices. The PixiJS renderer allows everyone to enjoy the power of hardware acceleration without prior knowledge of WebGL. Also, it's fast. Really fast.

If you want to keep up to date with the latest PixiJS news then feel free to follow us on Twitter @PixiJS and we will keep you posted! You can also check back on our site as any breakthroughs will be posted up there too!

We are now a part of the Open Collective and with your support you can help us make PixiJS even better. To make a donation, simply click the button below and we'll love you forever!

What to Use PixiJS for and When to Use It

PixiJS is a rendering library that will allow you to create rich, interactive graphics, cross platform applications, and games without having to dive into the WebGL API or deal with browser and device compatibility.

PixiJS has full WebGL support and seamlessly falls back to HTML5's canvas if needed. As a framework, PixiJS is a fantastic tool for authoring interactive content, especially with the move away from Adobe Flash in recent years. Use it for your graphics rich, interactive websites, applications, and HTML5 games. Out of the box cross-platform compatibility and graceful degradation mean you have less work to do and have more fun doing it! If you want to create polished and refined experiences relatively quickly, without delving into dense, low level code, all while avoiding the headaches of browser inconsistencies, then sprinkle your next project with some PixiJS magic!

Boost your development and feel free to use your imagination!


  • Website: Find out more about PixiJS on the official website.
  • Getting started: Check out @kittykatattack's comprehensive tutorial.
  • Examples: Get stuck right in and play around with PixiJS code and features right here!
  • Docs: Get to know the PixiJS API by checking out the docs.
  • Guide: Supplementary guide to the API documentation here.
  • Wiki: Other misc tutorials and resources are on the Wiki.


  • Forums: Check out the forum and Stackoverflow, both friendly places to ask your PixiJS questions.
  • Inspiration: Check out the gallery to see some of the amazing things people have created!
  • Chat: You can join us on Gitter To chat about PixiJS. We also now have a Slack channel. If you would like to join it please Send me an email ( and I will invite you in.


It's easy to get started with PixiJS! Simply download a prebuilt build!

Alternatively, PixiJS can be installed with npm or simply using a content delivery network (CDN) URL to embed PixiJS directly on your HTML page.

Note: After v4.5.0, support for the Bower package manager has been dropped. Please see the release notes for more information.

NPM Install

npm install pixi.js

There is no default export. The correct way to import PixiJS is:

import * as PIXI from 'pixi.js'

CDN Install (via cdnjs)

<script src=""></script>

Note: 5.1.3 can be replaced by any released version.


Thanks to @photonstorm for providing those last 2 examples and allowing us to share the source code :)


Want to be part of the PixiJS project? Great! All are welcome! We will get there quicker together :) Whether you find a bug, have a great feature request or you fancy owning a task from the road map above feel free to get in touch.

Make sure to read the Contributing Guide before submitting changes.

Current features

  • WebGL renderer (with automatic smart batching allowing for REALLY fast performance)
  • Canvas renderer (Fastest in town!)
  • Full scene graph
  • Super easy to use API (similar to the flash display list API)
  • Support for texture atlases
  • Asset loader / sprite sheet loader
  • Auto-detect which renderer should be used
  • Full Mouse and Multi-touch Interaction
  • Text
  • BitmapFont text
  • Multiline Text
  • Render Texture
  • Primitive Drawing
  • Masking
  • Filters
  • User Plugins

Basic Usage Example

import * as PIXI from 'pixi.js';

// The application will create a renderer using WebGL, if possible,
// with a fallback to a canvas render. It will also setup the ticker
// and the root stage PIXI.Container
const app = new PIXI.Application();

// The application will create a canvas element for you that you
// can then insert into the DOM

// load the texture we need
app.loader.add('bunny', 'bunny.png').load((loader, resources) => {
    // This creates a texture from a 'bunny.png' image
    const bunny = new PIXI.Sprite(resources.bunny.texture);

    // Setup the position of the bunny
    bunny.x = app.renderer.width / 2;
    bunny.y = app.renderer.height / 2;

    // Rotate around the center
    bunny.anchor.x = 0.5;
    bunny.anchor.y = 0.5;

    // Add the bunny to the scene we are building

    // Listen for frame updates
    app.ticker.add(() => {
         // each frame we spin the bunny around a bit
        bunny.rotation += 0.01;

How to build

Note that for most users you don't need to build this project. If all you want is to use PixiJS, then just download one of our prebuilt releases. Really the only time you should need to build PixiJS is if you are developing it.

If you don't already have Node.js and NPM, go install them. Then, in the folder where you have cloned the repository, install the build dependencies using npm:

npm install

Then, to build the source, run:

npm run build

How to generate the documentation

The docs can be generated using npm:

npm run docs

The documentation uses webdoc in combination with this template pixi-webdoc-template. The configuration file can be found at webdoc.conf.json

Download Details: 
Author: pixijs
Source Code: 
License: MIT
#javascript #gamedev #webgl #canvas #pixijs #html5

pixijs: The HTML5 Creation Engine
Dylan  Iqbal

Dylan Iqbal


HTML, CSS & JavaScript Web Publishing: Covering HTML5 CSS3 and jQuery (PDF Book for FREE Download)

HTML CSS & JavaScript Web Publishing in One Hour a Day Sams Teach Yourself: Covering HTML5 CSS3 and jQuery

Thoroughly revised and updated with examples rewritten to conform to HTML5, CSS3, and contemporary web development practices, this easy-to-understand, step-by-step tutorial helps you quickly master the basics of HTML and CSS before moving on to more advanced topics such as graphics, video, and interactivity with JavaScript and jQuery.  
In just one hour a day, you’ll learn the skills you need to design, create, and maintain a professional-looking website. 

  • No previous experience required. By following each short, one-hour lesson in this book, anyone can learn the basics of web development.
  • Learn at your own pace. You can work through each lesson sequentially to make sure you thoroughly understand all the concepts and methodologies, or you can focus on specific lessons to learn the techniques that interest you most.
  • Test your knowledge. Each lesson ends with a Workshop section filled with questions, answers, and exercises for further study.

Learn how to...

  • Fully implement the HTML5 and CSS3 standards
  • Work with text and create links
  • Add images and graphics to your page
  • Use CSS to style a site and position elements on a page
  • Structure a page with HTML5 
  • Use responsive web design to make your pages look good on different-sized screens
  • Use JavaScript to add dynamic elements and interactivity on your pages
  • Leverage jQuery to add JavaScript features to your pages
  • Design for the mobile web
  • Get your site online and let people know it’s there
  • Optimize your site for search engines

Contents at a Glance 
PART I: Getting Started 1 What Is Web Publishing 2 Getting Your Tools in Order 3 Introducing HTML and CSS 
PART II: Creating Web Pages 4 Learning the Basics of HTML  5 Organizing Information with Lists 6 Working with Links 
PART III: Doing More with HTML and CSS 7 Formatting Text with HTML and CSS 8 Using CSS to Style a Site 9 Using Images on Your Web Pages 10 Building Tables 11 Using CSS to Position Elements on a Page 12 Designing Forms 13 Structuring a Page with HTML5 14 Integrating Multimedia: Video and Sound 15 Advanced CSS: Page Layout in CSS 16 Using Responsive Web Design 
PART IV: Using JavaScript and jQuery 17 Introducing JavaScript 18 Using jQuery 19 Using JavaScript in Your Pages 20 Working with Frames and Linked Windows 
PART V: Designing for Everyone 21 Designing for the Mobile Web 22 Designing for User Experience 
PART VI: Going Live on the Web 23 How to Publish Your Site 24 Taking Advantage of the Server 25 Search Engines and SEO 


#html #css #javascript #html5 #css3 #webdev #jquery #programming #developer #ebook #book

HTML, CSS & JavaScript Web Publishing: Covering HTML5 CSS3 and jQuery (PDF Book for FREE Download)