Thursday, July 7, 2016

Tutorial on HTML5 Canvas

     The canvas element is one the most important features that HTML5 introduced into the world of web development, allowing the creation of dynamic content in a webpage without having to rely on Flash (Which is notorious for it's plethora of flaws and vulnerabilities). It has since then fueled several popular webpages, and is an essential piece of knowledge for any web developer.

     As for myself, I have developed small games for fun that runs entirely on a canvas element. They are great fun and easy to make, only requiring basic knowledge of HTML and JavaScript.

    Here is a video I made that gives a very basic introduction to the HTML5 canvas, how to draw a box and write text onto it, and capture mouse clicks. Enjoy!


     I might continue this as a series and make more videos like this in the future.

     Here is the full source code of the program I used in the video:

<html>
<head><title>Canvas Tutorial</title></head>
<canvas id="stage"></canvas>

<script>

var stage=document.getElementById("stage");
stage.width=500;
stage.height=500;
var ctx=stage.getContext("2d");
ctx.fillStyle="silver";
ctx.fillRect(0,0,stage.width,stage.height);
ctx.fillStyle="black";
ctx.font="20px Impact"
ctx.fillText("AGZuniverse",50,50)
stage.addEventListener("click",clk);

var x=0;

var y=0;
function clk(event)
{
x=event.clientX;
y=event.clientY;
drawbox(x,y);
}

function drawbox(a,b)

{
ctx.beginPath();
ctx.fillStyle="blue";
ctx.rect(a,b,50,50);
ctx.fill();
ctx.strokeStyle="black";
ctx.stroke();
}

</script>

</html>

No comments:

Post a Comment