Разработка игр на HTML5 — Урок 1
Начиная с сегодняшнего дня, мы начинаем серию статей о разработке игр на HTML5. В нашей первой статье мы рассмотрим основы — работа с холстом, создание простых объектов, заливка и некоторые связанные обработчики событий с помощью мыши. Также обратите внимание на этом этапе, мы будем изучать эту основу, а не сразу работать в 3D с WebGL. Но мы вернемся к WebGL в будущем.
В каждой следующей статье мы будем делать что-то новое. В первый раз, когда мы создаем объект с семью вершинами, в этих вершинах мы будем рисовать круги, мы сможем перемещать эти вершины с помощью перетаскивания окружностей. Также мы заполняем наш объект результата полупрозрачным цветом. Я думаю, что этого достаточно для начала.
Вот наш демонстрационный и загружаемый пакет:
Live Demo
скачать в упаковке
Хорошо, скачайте файлы примеров и давайте начнем кодировать!
Шаг 1. HTML
Вот все html моего демо
index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>HTML5 Game step 1 (demo) | Script Tutorials</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<canvas id="scene" width="800" height="600"></canvas>
</div>
<footer>
<h2>HTML5 Game step 1</h2>
<a href="http://www.script-tutorials.com/html5-game-development-lesson-1" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
</footer>
</body>
</html>
Шаг 2. CSS
Здесь используются стили CSS.
CSS / main.css
/* general styles */
*{
margin:0;
padding:0;
}
body {
background-color:#bababa;
background-image: -webkit-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
background-image: -moz-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
background-image: -o-radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
background-image: radial-gradient(600px 300px, circle, #ffffff, #bababa 60%);
color:#fff;
font:14px/1.3 Arial,sans-serif;
min-height:1000px;
}
.container {
width:100%;
}
.container > * {
display:block;
margin:50px auto;
}
footer {
background-color:#212121;
bottom:0;
box-shadow: 0 -1px 2px #111111;
display:block;
height:70px;
left:0;
position:fixed;
width:100%;
z-index:100;
}
footer h2{
font-size:22px;
font-weight:normal;
left:50%;
margin-left:-400px;
padding:22px 0;
position:absolute;
width:540px;
}
footer a.stuts,a.stuts:visited{
border:none;
text-decoration:none;
color:#fcfcfc;
font-size:14px;
left:50%;
line-height:31px;
margin:23px 0 0 110px;
position:absolute;
top:0;
}
footer .stuts span {
font-size:22px;
font-weight:bold;
margin-left:5px;
}
h3 {
text-align:center;
}
/* tutorial styles */
#scene {
background-image:url(../images/01.jpg);
position:relative;
}
Шаг 3. JS
JS / JQuery-1.5.2.min.js
Мы будем использовать jQuery для нашей демонстрации. Это позволяет легко связывать различные события (для мыши и т. Д.). Следующий файл наиболее важен, потому что содержит всю нашу работу с графикой:
JS / script.js
var canvas, ctx;
var circles = [];
var selectedCircle;
var hoveredCircle;
// -------------------------------------------------------------
// objects :
function Circle(x, y, radius){
this.x = x;
this.y = y;
this.radius = radius;
}
// -------------------------------------------------------------
// draw functions :
function clear() { // clear canvas function
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function drawCircle(ctx, x, y, radius) { // draw circle function
ctx.fillStyle = 'rgba(255, 35, 55, 1.0)';
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function drawScene() { // main drawScene function
clear(); // clear canvas
ctx.beginPath(); // custom shape begin
ctx.fillStyle = 'rgba(255, 110, 110, 0.5)';
ctx.moveTo(circles[0].x, circles[0].y);
for (var i=0; i<circles.length; i++) {
ctx.lineTo(circles[i].x, circles[i].y);
}
ctx.closePath(); // custom shape end
ctx.fill(); // fill custom shape
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgba(0, 0, 255, 0.5)';
ctx.stroke(); // draw border
for (var i=0; i<circles.length; i++) { // display all our circles
drawCircle(ctx, circles[i].x, circles[i].y, (hoveredCircle == i) ? 25 : 15);
}
}
// -------------------------------------------------------------
// initialization
$(function(){
canvas = document.getElementById('scene');
ctx = canvas.getContext('2d');
var circleRadius = 15;
var width = canvas.width;
var height = canvas.height;
var circlesCount = 7; // we will draw 7 circles randomly
for (var i=0; i<circlesCount; i++) {
var x = Math.random()*width;
var y = Math.random()*height;
circles.push(new Circle(x,y,circleRadius));
}
// binding mousedown event (for dragging)
$('#scene').mousedown(function(e) {
var canvasPosition = $(this).offset();
var mouseX = e.layerX || 0;
var mouseY = e.layerY || 0;
for (var i=0; i<circles.length; i++) { // checking through all circles - are mouse down inside circle or not
var circleX = circles[i].x;
var circleY = circles[i].y;
var radius = circles[i].radius;
if (Math.pow(mouseX-circleX,2) + Math.pow(mouseY-circleY,2) < Math.pow(radius,2)) {
selectedCircle = i;
break;
}
}
});
$('#scene').mousemove(function(e) { // binding mousemove event for dragging selected circle
var mouseX = e.layerX || 0;
var mouseY = e.layerY || 0;
if (selectedCircle != undefined) {
var canvasPosition = $(this).offset();
var radius = circles[selectedCircle].radius;
circles[selectedCircle] = new Circle(mouseX, mouseY,radius); // changing position of selected circle
}
hoveredCircle = undefined;
for (var i=0; i<circles.length; i++) { // checking through all circles - are mouse down inside circle or not
var circleX = circles[i].x;
var circleY = circles[i].y;
var radius = circles[i].radius;
if (Math.pow(mouseX-circleX,2) + Math.pow(mouseY-circleY,2) < Math.pow(radius,2)) {
hoveredCircle = i;
break;
}
}
});
$('#scene').mouseup(function(e) { // on mouseup - cleaning selectedCircle
selectedCircle = undefined;
});
setInterval(drawScene, 30); // loop drawScene
});
I commented all necessary code, so I hope that you will not get lost here.
source: http://www.script-tutorials.com/html5-game-development-lesson-1/