HTML5 Canvas: Prvi poizkus


Moj prvi preizkus z novim elementom canvas v HTML5. Kot je navada, se najprej napiše “Pozdrav svetu”. Ker element canvas služi predvsem risanju (animaciji), je za to bolj kot tekst uveljavljena poskakujoča žogica.

[html]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>html5 canvas hello word</title>
<style type="text/css">
canvas {
background-color: #eee;
}
</style>
</head>
<body>
<canvas id="bball" width="500" height="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

<script src="myscript.js"></script>
</body>
</html>[/html]

Ddatoteka myscript.js vsebuje pripravo risalne površine in implementacijo logike odbijajoče se žogice od vseh robov risalne površine.

[javascript]
var canvas = document.getElementById("bball");
var ctx = canvas.getContext("2d");

var width = parseInt(canvas.getAttribute("width"));
var height = parseInt(canvas.getAttribute("height"));

var radius = 20;
var posx = radius;
var posy = radius;
var speedx = 2;
var speedy = 4;
var directionx = 1;
var directiony = 1;

function drawCircle() {
ctx.beginPath();
ctx.arc(posx, posy, radius, 0, Math.PI*2, true);
ctx.fill();
}

function clear() {
ctx.clearRect(0, 0, width, height);
}

function init() {
return setInterval(draw, 30);
}

function draw() {
clear();
drawCircle();

posx += directionx*speedx;
posy += directiony*speedy;

if (posx + radius > width || posx < radius)
directionx *= -1;
if (posy + radius > height || posy < radius)
directiony *= -1;
}

init();
[/javascript]

Zgornjo kodo si poglejte v delovanju na sledeči povezavi.