The HTML page is used to create the canvas, the coding for the HTML page is given below
The above screen shot shows the canvas created using HTML
<html>
<head>
<title>HTML5 Avoider Game</title>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<canvas id="gameCanvas" onclick="drawAvatar();" width="400" height="300"></canvas>
<p>From <a href="http://codemonkeyy.blogspot.com" rel="external">Learn to code @ "CODEMONKEYY"</a>.</p>
</body>
</html>
CSS is used to change the size of the canvas and to make the cursor disappear.The CSS coding is provided below
body {
background: #ffffff;
text-align: center;
padding: 20px;
color: #575757;
font: 14px/21px Arial,Helvetica,sans-serif;
}
a {
color: #B93F14;
}
a:hover {
text-decoration: none;
}
ol {
width: 600px;
text-align: left;
margin: 15px auto
}
canvas {
border: 1px solid black;
cursor: none;// Remove the cursor
}
Java script is used to create duplicate images and to move the image around the canvas with the cursor. The java script coding is provided below
function alertSeveralTimes() {
alert("Hello!");
alert("Welcome to codemonkeyy.");
alert("wanna code?");
}
function changeCanvasSize() {
var gameCanvas = document.getElementById("gameCanvas");
var avatarImage = new Image();
gameCanvas.width = 600;
gameCanvas.height = 800;
avatarImage.src = "img/avatar.png";
gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
}
function drawAvatar() {
var gameCanvas = document.getElementById("gameCanvas");
var avatarImage = new Image();
avatarImage.src = "img/avatar.png";
gameCanvas.getContext("2d").drawImage(avatarImage, Math.random() * 100, Math.random() * 100);
gameCanvas.addEventListener("mousemove", redrawAvatar);
}
function redrawAvatar(mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas");
var avatarImage = new Image();
var enemyImage = new Image();
avatarImage.src = "img/avatar.png";
enemyImage.src = "img/enemy.png";
gameCanvas.width = 400; //this erases the contents of the canvas
gameCanvas.getContext("2d").drawImage(avatarImage, mouseEvent.offsetX, mouseEvent.offsetY);
gameCanvas.getContext("2d").drawImage(enemyImage, 250, 150);
if (mouseEvent.offsetX > 150 && mouseEvent.offsetX < 250 && mouseEvent.offsetY > 100 && mouseEvent.offsetY < 200) {
alert("You hit the monkey!");
}
}
The screen shot below shows the simple game developed using HTML5, try it for your self.
Use these two images for the avatars in the game
HAVE FUN
No comments:
Post a Comment