{lang: ‘ru’}

уроки html5, html5 games, html5 canvas, html5 примерыСегодня 2 урок по разработке игр на HTML5 и мы продолжаем изучать основы. Я покажу Вам, как рисуется текст и применяются пользовательские шрифты, как заполнить объекты градиентом, как создать анимацию, и самое главное: элемент пользовательского интерфейса — кнопка.

С предыдущим уроком можете ознакомиться здесь: Урок 1. Я буду работать с нашим предыдущим скриптом — мы будем только развивать и оптимизировать его. Я собираюсь нарисовать текст, используя специальный шрифт, подвижный объект (квадрат), заполненный градиентом, и кнопку «Play/Pause», которая влияет на анимацию.

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

Демо Исходники

Шаг 1. HTML

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>Разработка игр на HTML5 - Урок 2 | officialplat-tt.ru</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 - Урок 2</h2>
            <a href="http://officialplat-tt.ru/?p=1581" 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 {
    background-image:url(../images/01.jpg);
    position:relative;
}

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

Step 3. JS

js/jquery-1.5.2.min.js

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

js/script.js

var canvas, ctx;
var circles = [];
var selectedCircle;
var hoveredCircle;
var button;
var moving = false;
var speed = 2.0;

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

// объекты :

function Circle(x, y, radius){
    this.x = x;
    this.y = y;
    this.radius = radius;
}

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 clear() { // функция очистки canvas
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawCircle(ctx, x, y, radius) { // функция рисует окружность
    ctx.fillStyle = 'rgba(255, 35, 55, 1.0)';

    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI*2, true);
    ctx.closePath();

    ctx.fill();

    ctx.lineWidth = 1;
    ctx.strokeStyle = 'rgba(0, 0, 0, 1.0)';
    ctx.stroke(); // отрисовка границы
}

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

    // рисуем текстовый заголовок
    ctx.font = '42px Aksent';
    ctx.textAlign = 'center';
    ctx.fillStyle = '#ffffff';
    ctx.fillText('Урок #2', ctx.canvas.width/2, 50);

    var bg_gradient = ctx.createLinearGradient(0, 200, 0, 400);
    bg_gradient.addColorStop(0.0, 'rgba(255, 0, 0, 0.8)');
    bg_gradient.addColorStop(0.5, 'rgba(0, 255, 0, 0.8)');
    bg_gradient.addColorStop(1.0, 'rgba(0, 0, 255, 0.8)');

    ctx.beginPath(); // начало фигуры
    ctx.fillStyle = bg_gradient;
    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(); // конец фигуры
    ctx.fill(); // заполнение фигуры

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

    // изменение направления
    if (circles[0].x <= 300 || circles[0].x >= 385) {
        speed = -speed;
    }

    // Поведение центрального объекта
    if (moving) {
        circles[0].x -= speed;
        circles[0].y -= speed;
        circles[1].x += speed;
        circles[1].y -= speed;
        circles[2].x += speed;
        circles[2].y += speed;
        circles[3].x -= speed;
        circles[3].y += speed;
    }

    drawCircle(ctx, circles[0].x, circles[0].y, (hoveredCircle == 0) ? 25 : 15);
    drawCircle(ctx, circles[1].x, circles[1].y, (hoveredCircle == 1) ? 25 : 15);
    drawCircle(ctx, circles[2].x, circles[2].y, (hoveredCircle == 2) ? 25 : 15);
    drawCircle(ctx, circles[3].x, circles[3].y, (hoveredCircle == 3) ? 25 : 15);

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

    // отрисовка текста
    ctx.font = '20px Aksent';
    ctx.fillStyle = '#ffffff';
    ctx.fillText('Play/Pause', 135, 480);
    ctx.fillText(button.state, 135, 515);
}

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

// инициализация

$(function(){
    canvas = document.getElementById('scene');
    ctx = canvas.getContext('2d');

    var circleRadius = 15;
    var width = canvas.width;
    var height = canvas.height;

    // добавим 4 окружности
    circles.push(new Circle(width / 2 - 20, height / 2 - 20, circleRadius));
    circles.push(new Circle(width / 2 + 20, height / 2 - 20, circleRadius));
    circles.push(new Circle(width / 2 + 20, height / 2 + 20, circleRadius));
    circles.push(new Circle(width / 2 - 20, height / 2 + 20, circleRadius));

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

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

        var mouseX = e.layerX || 0;
        var mouseY = e.layerY || 0;
        for (var i=0; i<circles.length; i++) { // проверка всех окружностей - клавиша мыши нажата внутри окружности или нет
            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;
            }
        }

        // поведение кнопки
        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 (selectedCircle != undefined) {
            // var canvasPosition = $(this).offset();

            var radius = circles[selectedCircle].radius;
            circles[selectedCircle] = new Circle(mouseX, mouseY,radius); // изменяем позицию выбранной окружности
        }

        hoveredCircle = undefined;
        for (var i=0; i<circles.length; i++) { // проверка всех окружностей - клавиша мыши нажата внутри окружности или нет
            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;
                circles[hoveredCircle] = new Circle(circleX, circleY, 25);
                break;
            }
        }

        // поведение кнопки
        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) { // событие mouseup - очистка выбранной окружности
        selectedCircle = undefined;

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

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

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

1. Мы можем нарисовать текст с пользовательским шрифтом, используя следующий код:

ctx.font = '42px Aksent';
ctx.textAlign = 'center';
ctx.fillStyle = '#ffffff';
ctx.fillText('Урок #2', ctx.canvas.width/2, 50);

2. Применение градиентной заливки:

var bg_gradient = ctx.createLinearGradient(0, 200, 0, 400);
bg_gradient.addColorStop(0.0, 'rgba(255, 0, 0, 0.8)');
bg_gradient.addColorStop(0.5, 'rgba(0, 255, 0, 0.8)');
bg_gradient.addColorStop(1.0, 'rgba(0, 0, 255, 0.8)');
ctx.fillStyle = bg_gradient;

3. Кнопка — я использовал 1 спрайт со всеми тремя состояниями кнопки. Также я добавил обработчики событий на наведение и нажатие кнопки. Загрузка и отрисовка выполняется в этом участке кода:

buttonImage = new Image();
buttonImage.src = 'images/button.png';
.......
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, width, height);

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

fonts/Aksent.ttf  и  images/button.png

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

Демо Исходники



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


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