Tag Archives: canvas

Adding sound to a game in PlayCanvas

This tutorial explains how to add sound effects and background music to your game in PlayCanvas. You can add sounds that can be heard from anywhere in the game or attach sounds to objects that can only be heard when your character is near them in the game.

You can also add sounds that automatically play and loop in the background and you can also control when sounds play and stop using code. Using code to control sound will be explained in the next tutorial. Watch the video below to see how to add sound to your game.

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Rigid Bodies and Collision in PlayCanvas

This tutorial explains how to add the Rigid Body and Collision components to objects in your game so that your objects can move around and interact in a realistic way and so that you can detect when different objects collide in your game.

Rigid bodies allow the objects in your game to act under the control of physics. This means that your objects will be able to receive forces and move around in a realistic way. In order for an object to be able to interact with other objects and be under the influence of gravity or different forces (that can be controlled by scripts), it must have a Rigid Body component. You can change the properties of a rigid body such as friction, restitution (bounciness), mass, and so on.

The Collision component in PlayCanvas will give an object its physical form and change the way it behaves. There are several types of colliders (collision types) such as box, sphere, capsule, etc. If you give a box object a box collider, it will behave like a box. This means it will move around, slide, bounce, fall, and collide with other objects the way that a box would. If you give a sphere or ball object a sphere collider, then it will be able to bounce and roll around just like a real sphere or ball would. The Collision component is necessary for collision detection and triggers (something we will look at in another tutorial).

Watch the video below and then scroll down to see the sample code used for basic collision detection in the video.

Sample code for the collider.js script:

pc.script.create('collider', function (app) {
    // Creates a new Collider instance
    var Collider = function (entity) {
        this.entity = entity;
    };

    Collider.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            this.entity.collision.on('collisionstart', this.onCollisionStart, this);
        },

        onCollisionStart: function(result){
            if(result.other.rigidbody){
                this.entity.destroy();
            }
        }
        
        
    };

    return Collider;
});

Drawing quadratic curves

This tutorial explains how to draw quadratic curves on the HTML canvas. We can use the quadraticCurveTo() method to draw a quadratic curve on the canvas.

The quadratic curve is defined by three things: the context point, the control point, and the ending point. These curves can also be styled using the lineWidth, stroke style and lineCap properties just like regular lines.

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Quadratic curves</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(300,50);
 ctx.quadraticCurveTo(300,100,350,100); // (control point x, control point y, x, y)
 ctx.lineTo(350,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Drawing arcs using the arcTo method

This tutorial explains how to draw arcs using the arcTo method. You will learn how to draw arcs and join arcs to other lines on the canvas.

This is what the arc attached to lines will look like:

Screen Shot 2015-05-08 at 6.56.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>The arcTo method</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(200,50);
 ctx.arcTo(250,50,250,100,50); // x1, y1, x2, y2, radius
 ctx.lineTo(250,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing quadratic curves

Clipping shapes on the canvas

This tutorial will explain how to clip shapes on the canvas. The clipped shape example in the video will look like this:

Screen Shot 2015-05-08 at 7.01.35 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Clipping shapes</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.rect(50, 50, 100, 100) // x, y, width, height
 // we will clip one rectangle with the other 
 ctx.clip();
 ctx.rect(0, 0, 100, 100)
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="200" height="200">
</body>
</html>

Next tutorial: Drawing arcs and circles on the canvas

Drawing paths on the canvas

This tutorial explains how to draw paths on the canvas. Paths can be used to build shapes by creating lines, filling the path, and filling the background with a colour, as seen in the example below.

Screen Shot 2017-04-14 at 5.06.13 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Drawing paths</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.beginPath(); // this will reset the current default path
 ctx.moveTo(50,50); // x, y coordinates of start of line
 ctx.lineTo(250,50); // creates new line to these x, y coordinates
 ctx.lineTo(250,150); // creates another line to these x, y coordinates
 ctx.lineTo(50,150);
 ctx.fill();
 ctx.closePath(); // this will close the path to complete the rectangle (adds the last line on the left side of rectangle)
 ctx.stroke(); // strokes the current path
 alert(ctx.isPointInPath(75,75)); // returns a true/false value indicating whether the specified point is within a path
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Clipping shapes on the canvas

Joining lines on the canvas

This tutorial explains how to join lines on the canvas. The lines that we will join in this tutorial will end up looking like this:

Screen Shot 2015-05-08 at 6.59.43 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Joining lines</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth = 20;
 ctx.lineCap = "butt"; // options are: square, round, butt
 ctx.lineJoin = "round"; // options are: round, bevel, miter
 //ctx.miterLimit = 3;
 //ctx.setLineDash([20,10]); //adds dashes -length of dash,length of gap between dash
 //ctx.lineDashOffset = 20;
 
 ctx.beginPath();
 ctx.moveTo(50,50);
 ctx.lineTo(150,250);
 ctx.lineTo(250,50);
 ctx.lineTo(150,50);
 ctx.strokeStyle="#FF0000";
 ctx.stroke();
 //ctx.fill(); will add a fill
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="300" height="300">
</body>
</html>

Next tutorial: Drawing paths on the canvas

Styling lines on the canvas

In the previous tutorial we looked at how to draw lines on the canvas. In this tutorial we will style lines on the canvas by changing the following properties:

  • colour
  • width
  • line cap (shape on the ends of a line) for a line on the canvas

The line that we will create will look like this:

Screen Shot 2015-05-08 at 6.58.05 pm

Watch the video below and then scroll down the page to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
 <title>Styling lines on the canvas</title>
 <style>
 #myCanvas{
 background-color:#FFFFFF;
 border: 1px solid #000000;
 }
 </style>
</head>
 
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth=20; // specify the width of the line
 ctx.lineCap="round"; // lineCap options are square, round, butt
 ctx.moveTo(50,50); // x,y positions - where the line begins
 ctx.lineTo(250,250); // x,y positions - where the line ends
 ctx.strokeStyle="#0000FF"; // specify the colour of the line
 ctx.stroke(); // draw the line
 }
 window.onload=draw; // run the draw function when the page loads
 </script>
 <canvas id="myCanvas" width="300" height="300">
</body>
</html>

Next tutorial: Joining lines on the canvas

Using colour gradients and patterns

The code below shows how to use linear and radial gradients to fill rectangle shapes.

The three shapes will look like this (linear gradient on top left, radial gradient on top right, image pattern on bottom left side):

Screen Shot 2015-05-08 at 6.53.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the code:

<!DOCTYPE html>
<html>
<head>
 <title>Gradients and patterns</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 var patternImage = new Image();
 patternImage.src = "pattern.png";
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 var gradient = ctx.createLinearGradient(0,0,150,0); // x1, y1, x2, y2 
 gradient.addColorStop(0, "red");
 gradient.addColorStop(0.5, "yellow");
 gradient.addColorStop(1, "green");
 ctx.fillStyle = gradient;
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 
 var gradient2 = ctx.createRadialGradient(350,100,0,350,100,200);
 // ctx.createRadialGradient parameters are x1, y1, r1, x2, y2, r2
 gradient2.addColorStop(0, "yellow");
 gradient2.addColorStop(1, "blue");
 ctx.fillStyle = gradient2;
 ctx.strokeStyle = "blue";
 ctx.fillRect(250,0,200,200);
 ctx.strokeRect(250,0,200,200);
 
 var pattern = ctx.createPattern(patternImage, "repeat");
 ctx.fillStyle = pattern;
 ctx.strokeStyle = gradient;
 ctx.lineWidth = 20;
 ctx.fillRect(20,150,200,200);
 ctx.strokeRect(20,150,200,200);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="500" height="400">
</body>
</html>

Next tutorial: Simple animations using JavaScript

Simple animations using JavaScript

This tutorial explains how to use the HTML5 canvas element and JavaScript to animate a div in a webpage. Below is a preview of what the animation will look like. Scroll down to see the code.

animdiv

Refer to the comments in the code below to find out what is happening on each line.

<html>
<head>
<title>My animation</title>
<style type="text/css">
 
#animatedBox{
 /* simple box */
 position:absolute; /* The element is positioned relative to its first positioned (not static) ancestor element */
 top:30px; /* This is the position of the box from the top */
 width:200px; /* This is the width of the box */
 line-height:20px; /* This is the height of the box */
 background:#58FA82; /* This is the background colour of the box */
 border:1px solid #0B610B; /* This is the border thickness and border colour of the box */
 padding:10px; /* This is the padding amount around the text in the box */
 
 /* Hint: Get colour codes from http://html-color-codes.info/ */
}
 
</style>
<script type="text/javascript">
 
var box ; // create the variable we will use as the object to animate
 
function doMove() {
 box.style.left = parseInt(box.style.left)+1+'px'; // parseInt parses a string and returns an integer, moves 1 pixel from left
 setTimeout(doMove,20); // call doMove in 20 milliseconds
}
 
function init() {
 box = document.getElementById('animatedBox'); // get the "box" object
 box.style.left = '0px'; // set its initial position to 0px
 doMove(); // call the doMove function to start animating!
}
 
 
window.onload = init; // load the init function when the page loads
 
</script>
</head>
 
<body>
 
<div id="animatedBox">
 <b>My animation</b>
</div>
 
</body>
</html>

Next tutorial: Animating (moving) an image using JavaScript

Drawing arcs and circles with the HTML5 canvas

This tutorial explains how to use the HTML5 canvas and JavaScript to draw circles and arcs on the canvas. The code below shows how to draw a full circle, but you can easily modify it to draw arcs (the circle is made up of arcs).

In this example, the circle will be inside a canvas with a black border and will look like this:

Screen Shot 2015-03-12 at 10.47.58 am

Watch the video below and then scroll down to see the sample code.

Refer to the comments in the code to find out what is happening on each line of the code.

<!DOCTYPE html>
<html>
<head>
 <title>Arcs and circles</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.arc(150,150,100,0,Math.PI*2,false); // x, y, radius, startAngle, endAngle, true/false (for clockwise and anticlockwise)
 // Math.PI gives semi-circle
 // Math.PI*2 gives full circle
 // Numbers can also be used instead of Math.P eg. 6.28
 // try using numbers less than 6.28 to see how you get less of a circle
 ctx.stroke();
 //try doing semi-circle that is (flipped over) by chaning false to true
 
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing arcs using the arcTo method

Drawing lines using the HTML5 canvas

This tutorial explains how to use the HTML5 canvas element to draw lines. The line that will be drawn will be inside a canvas with a  grey border. It will look like this:

Screen Shot 2015-05-04 at 8.51.12 pm

Watch the video below to see how to draw lines and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Drawing lines on canvas</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(0,0);
 ctx.lineTo(200,100);
 ctx.strokeStyle="#FF0000";
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="200" height="100">
</body>
</html>

Next tutorial: Styling lines on the canvas

Using the HTML5 canvas to draw shapes

The code below shows how to use the HTML5 canvas and JavaScript in a webpage to draw objects. In this example, the object will be a simple rectangle shape inside a canvas with a grey border. The rectangle will be filled with red and have a blue border. It will look like this:

Screen Shot 2015-05-04 at 7.53.26 pm

You can use the canvas for drawings, animations, and even games. Watch the video below to see how to create a canvas and draw a rectangle shape, then scroll down to see the code.

Check out the sample code below. You can view all the different HTML colour codes that you can use here.

<!DOCTYPE html>
<html>
<head>
 <title>Simple canvas with rectangle drawing</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.fillStyle = "red";
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="200" height="100">
</body>
</html>

Next tutorial: Drawing lines using the HTML5 canvas element