{lang: 'ru'}

уроки html5, html5 games, html5 canvas, html5 примерыCегодня мы продолжаем изучать HTML5 на примере создания игр. В этот раз мы добавим анимацию и еще несколько интересных особенностей. В конце урока у нас получится космический корабль, который летит через космическое пространство, и новый элемент — диалог. Диалог будет содержать две страницы, и наша кнопка будет управлять этим диалогом.

С предыдущим уроком Вы можете ознакомиться перейдя по ссылке: Разработка игр на HTML5 — Урок 2. За основу будет взят скрипт, который мы создали в прошлый раз.

Вот наши демо и архив с исходниками:

Demo Исходники

Шаг 1. HTML

<!DOCTYPE html>
<html lang="ru" >
    <head>
        <meta charset="utf-8" />
        <title>Разработка игр на HTML5 - Урок 3 | 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 - Урок 3</h2>
            <a href="http://officialplat-tt.ru/?p=1598" class="stuts">Вернуться на <span>officialplat-tt.ru</span></a>
        </footer>
    </body>
</html>

Шаг 2. CSS

/* general styles */
*{
    margin:0;
    padding:0;
}

@font-face {
    font-family: "Aksent";
    src: url("../fonts/Aksent.ttf");
}

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;
}

#scene {
    position:relative;
}

Обратите внимание на ‘@font-face’. С помощью него мы подключаем свой шрифт (ttf).

Step 3. JS

js/jquery-1.5.2.min.js

В примере мы будем использовать jQuery. Так будет проще обрабатывать различные события. Следующий файл самый важный, так как он работает с графикой.

js/script.js

var canvas, ctx;
var button;
var backgroundImage;
var spaceShip;
var iBgShiftX = 1024;
var bDrawDialog = true;
var iDialogPage = 1;
// -------------------------------------------------------------

// объекты :
function Button(x, y, w, h, state, image) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.state = state;
    this.imageShift = 0;
    this.image = image;
}
function SpaceShip(x, y, w, h, image) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.image = image;
    this.bDrag = false;
}
// -------------------------------------------------------------

// фукнции отрисовки :

function clear() { // функция очистки canvas
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawDialog() { // функция отрисовки диалога
    if (bDrawDialog) {
        var bg_gradient = ctx.createLinearGradient(0, 200, 0, 400);
        bg_gradient.addColorStop(0.0, 'rgba(160, 160, 160, 0.8)');
        bg_gradient.addColorStop(1.0, 'rgba(250, 250, 250, 0.8)');

        ctx.beginPath(); // начало фигуры
        ctx.fillStyle = bg_gradient;
        ctx.moveTo(100, 100);
        ctx.lineTo(700, 100);
        ctx.lineTo(700, 500);
        ctx.lineTo(100, 500);
        ctx.lineTo(100, 100);
        ctx.closePath(); // конец фигуры
		ctx.fill(); // заполнение фигуры

        ctx.lineWidth = 2;
        ctx.strokeStyle = 'rgba(128, 128, 128, 0.5)';
        ctx.stroke(); // отрисовка границы

        // отрисовка текста
        ctx.font = '42px Aksent';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'top';
        ctx.shadowColor = '#000';
        ctx.shadowOffsetX = 2;
        ctx.shadowOffsetY = 2;
        ctx.shadowBlur = 2;
        ctx.fillStyle = '#fff';
        if (iDialogPage == 1) {
            ctx.fillText('Урок #3', ctx.canvas.width/2, 150);
            ctx.font = '24px Aksent';
            ctx.fillText('После закрытия диалогового окна Вы сможете', ctx.canvas.width/2, 250);
            ctx.fillText('передвигать корабль с помощью мыши', ctx.canvas.width/2, 280);
        } else if (iDialogPage == 2) {
            ctx.fillText('Вторая страница диалога', ctx.canvas.width/2, 150);
            ctx.font = '24px Aksent';
            ctx.fillText('Любой текст', ctx.canvas.width/2, 250);
        }
    }
}

function drawScene() { // главная функция отрисовки
    clear(); // очистить canvas

    // отрисовка фона
    iBgShiftX -= 10;
    if (iBgShiftX <= 0) {
        iBgShiftX = 1024;
    }
    ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1024, 768, 0, 0, 800, 600);

    // отрисовка корабля
    ctx.drawImage(spaceShip.image, 0, 0, spaceShip.w, spaceShip.h, spaceShip.x-128, spaceShip.y-128, spaceShip.w, spaceShip.h);

    // отрисовка диалога
    drawDialog();

    // отрисовка кнопки
    ctx.drawImage(button.image, 0, button.imageShift, button.w, button.h, button.x, button.y, button.w, button.h);

    // отрисовка текста на кнопке
    ctx.font = '22px Aksent';
    ctx.fillStyle = '#ffffff';
    ctx.fillText('next/hide/show', 400, 465);
    ctx.fillText('dialog', 400, 500);
}

// -------------------------------------------------------------

// инициализация
$(function(){
    canvas = document.getElementById('scene');
    ctx = canvas.getContext('2d');

    var width = canvas.width;
    var height = canvas.height;

    // загрузка фонового изображения
    backgroundImage = new Image();
    backgroundImage.src = 'images/stars.jpg';
    backgroundImage.onload = function() {
    }
    backgroundImage.onerror = function() {
        console.log('Ошибка загрузки фонового изображения.');
    }

    // инициализация корабля
    var oSpShipImage = new Image();
    oSpShipImage.src = 'images/space_ship.png';
    oSpShipImage.onload = function() {
    }
    spaceShip = new SpaceShip(400, 300, 256, 256, oSpShipImage);

    // загрузка кнопки
    var buttonImage = new Image();
    buttonImage.src = 'images/button.png';
    buttonImage.onload = function() {
    }
    button = new Button(310, 450, 180, 120, 'normal', buttonImage);

    $('#scene').mousedown(function(e) { // привязываем событие нажатия мыши (для перетаскивания)

        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;

        if (!bDrawDialog &&
            mouseX > spaceShip.x-128 && mouseX < spaceShip.x-128+spaceShip.w &&
            mouseY > spaceShip.y-128 && mouseY < spaceShip.y-128+spaceShip.h) {

            spaceShip.bDrag = true;
            spaceShip.x = mouseX;
            spaceShip.y = mouseY;
        }

        // поведение кнопки
        if (mouseX > button.x && mouseX < button.x+button.w && mouseY > button.y && mouseY < button.y+button.h) {
            button.state = 'pressed';
            button.imageShift = 262;
        }
    });

    $('#scene').mousemove(function(e) { // привязываем событие движения мыши
        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;

        if (!bDrawDialog && spaceShip.bDrag) {
            spaceShip.x = mouseX;
            spaceShip.y = mouseY;
        }

        // поведение кнопки
        if (button.state != 'pressed') {
            button.state = 'normal';
            button.imageShift = 0;
            if (mouseX > button.x && mouseX < button.x+button.w && mouseY > button.y && mouseY < button.y+button.h) {
                button.state = 'hover';
                button.imageShift = 131;
            }
        }
    });

    $('#scene').mouseup(function(e) { // привязываем событие отжатия кнопки
        spaceShip.bDrag = false;

        // поведение кнопки
        if (button.state == 'pressed') {
            if (iDialogPage == 0) {
                iDialogPage++;
                bDrawDialog = !bDrawDialog;
            } else if (iDialogPage == 2) {
                iDialogPage = 0;
                bDrawDialog = !bDrawDialog;
            } else {
                iDialogPage++;
            }
        }
        button.state = 'normal';
        button.imageShift = 0;
    });

    setInterval(drawScene, 30); // скорость отрисовки
});

Вот несколько пояснений о новых возможностях.

1. Отрисовка анимации космоса со звездами (всё очень просто, меняются координаты изображения)

iBgShiftX -= 10;
if (iBgShiftX <= 0) {
    iBgShiftX = 1024;
}
ctx.drawImage(backgroundImage, 0 + iBgShiftX, 0, 1024, 768, 0, 0, 800, 600);

Шаг 4. Дополнительные файлы

fonts/Aksent.ttf,  images/button.png, images/space_ship.png и images/stars.jpg

Файлы будут доступны в исходниках.

Demo Исходники



Неплохой у нас получился звездолет? :) Я буду рад , если Вы оставите комментарий и поделитесь ссылкой с друзьями. Удачи!

Получайте новые статьи блога прямо себе на почту