Download presentation
Presentation is loading. Please wait.
Published bySharlene Nichols Modified over 8 years ago
1
HTML5 ProgLan HTML5 Making a Game on the Canvas Part 1
2
More on the Canvas The next few sessions we will look at the HTML5 Canvas from the perspective of creating a Break- Out type game
3
Create the HTML document Break Out!
4
Create the Canvas The first thing we need to do is create an instance of the element so that we can start to draw on it. If you look in the source for this page, you'll see a declaration that looks like this:
5
Create a Circle //get a reference to the canvas Var ctx = document.getElementById("g ameboard").getContext("2d" );//draw a circle ctx.beginPath(); ctx.arc(75, 75, 10, 0, Math.PI*2, true); ctx.closePath(); ctx.fill();
6
Add Color var ctx = $('#canvas')[0].getContext("2d"); ctx.fillStyle = "#00A308"; ctx.beginPath(); ctx.arc(220, 220, 50, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); ctx.fillStyle = "#FF1C0A"; ctx.beginPath(); ctx.arc(100, 100, 100, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); //the rectangle is half transparent ctx.fillStyle = "rgba(255, 255, 0,.5)" ctx.beginPath(); ctx.rect(15, 150, 120, 120); ctx.closePath(); ctx.fill();
7
Movement var x = 150; var y = 150; var dx = 2; var dy = 4; var ctx; function init() { ctx = $('#canvas')[0].getContext("2d"); return setInterval(draw, 10); } function draw() { ctx.clearRect(0,0,300,300); ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); x += dx; y += dy; } init();
8
Simplifying Coding //BEGIN LIBRARY CODE var x = 150; var y = 150; var dx = 2; var dy = 4; var WIDTH; var HEIGHT; var ctx; function init() { ctx = $('#canvas')[0].getContext("2d"); WIDTH = $("#canvas").width(); HEIGHT = $("#canvas").height(); return setInterval(draw, 10); } function circle(x,y,r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); } function rect(x,y,w,h) { ctx.beginPath(); ctx.rect(x,y,w,h); ctx.closePath(); ctx.fill(); } function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); } //END LIBRARY CODE function draw() { clear(); circle(x, y, 10); x += dx; y += dy; } init();
9
Bouncing against walls function draw() { clear(); circle(x, y, 10); if (x + dx > WIDTH || x + dx < 0) dx = -dx; if (y + dy > HEIGHT || y + dy < 0) dy = -dy; x += dx; y += dy; } init();
10
The game is incomplete
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.