Showing posts with label canvas. Show all posts
Showing posts with label canvas. Show all posts

Tuesday, March 31, 2015

Game canvas

EaselJS
http://www.createjs.com/Docs/EaselJS/modules/EaselJS.html
var stage;

        function init() {
  stage = new createjs.Stage(document.getElementById("mycanvas"));

  var spriteSheet = new createjs.SpriteSheet({
   // số lượng frame hiện ra trong mỗi giây
   framerate: 8,
   // hình ảnh
   "images": ["img/runningcat.png"],
   // width: chiều rộng của 1 sprite, height: chiều cao của 1 sprite
   // count: số lượng sprite sẽ được duyệt
   // có thể có thêm regX: 0, regY:0 : là canh tọa độ hiển thị (không bắt buộc)
   "frames": {width:512, height:256, count: 8, regX: 0, regY:0},
   "animations": {
    // 0 - 7 sẽ hiện sprite từ 0 đến 7
    "run": [0, 7, "run", 1],
    // 5 - 7 là sẽ hiện sprite từ 5 - 7 rồi quay lại "run"
    "jump": [5, 7, "run"]
   }
  });

  var grant = new createjs.Sprite(spriteSheet, "run");
  grant.x = 0;
  grant.y = 0;

  stage.addChild(grant);
  createjs.Ticker.timingMode = createjs.Ticker.RAF;
  createjs.Ticker.addEventListener("tick", stage);
 }

Trang html: 
Thẻ body: thêm vào onload = init();
Trong body, thêm thẻ canvas:

TẠO ÂM THANH CHO CANVAS


        sounds = [
  {src: "R-Damage.ogg", id: 1}
 ];
 createjs.Sound.alternateExtensions = ["mp3"];
        // nếu cho hàm này chạy sẽ gọi function soundLoaded khi âm thanh hoàn tất
 //createjs.Sound.addEventListener("fileload", createjs.proxy(soundLoaded, this));
 createjs.Sound.registerSounds(sounds, "audio/");
// gọi hàm này playSound(); ở nơi mà ta cần phát âm thanh, truyền vào id của âm thanh đó
// ví dụ : playSound(1);
function playSound(target) {
 var soundInstance = createjs.Sound.play(target, createjs.Sound.INTERRUPT_NONE, 0, 0, false, 1);
}
  • Note : Âm thanh gồm 2 file mp3 và ogg

CÁCH LƯU HÌNH ẢNH TRONG 1 LIST

/**
* Khai bao vùng trời, mặt đất
*/
function createMain() {
 manifest = [
  {src: "ground.png", id: "ground"},
  {src: "sky.png", id: "sky"},
  {src: "BlockA0.png", id: "BlockA0"}
 ];

 loader = new createjs.LoadQueue(false);
 loader.addEventListener("complete", handleComplete);
 loader.loadManifest(manifest, true, "img/");
}
​
- chức năng của hàm này là lưu lại những hình ảnh ta cần sử dụng sau này, được lấy từ thư mục /img

Cách sử dụng : 

//khai báo bầu trời
var skyImg = loader.getResult("sky");
sky = new createjs.Shape();
sky.graphics.beginBitmapFill(skyImg).drawRect(0, 0, wCanvas, hCanvas - 79);

stage.addChild(sky);
  • Note : Khi cần viết 1 hàm nào đê thực hiện chức năng sau này thì hãy viết trong function handleComplete();

CÁCH TẠO BẢN ĐỒ (GAME MÊ CUNG)


ví dụ sử dụng 1 mảng ma trận : 

23224252562826272290
31.2..............23
7.2..24.2.2323.24.25
4.5.2...2.2....2..26
2.9.2.3.0.2.22.2.227
3.6.3.2.9...22....28
4.2.2.8.2825762.2..6
4...2.6.22......22.6
02.2..9.22.2.2.2...9
9..2.22...23.2.2.220
8.22.29.2.3..2.2.223
5.22..0.0.27.2.2...4
6...2.206.40.02922.5
6...5............8.5
232942529628262722.x

'1': nơi hiện ra của nhân vật
'x': exit (hoàn thành vòng chơi)

'.': nơi nhân vật có thể di chuyển được

2 -> 9, 0: là các bức tường
//Loop over every tile position,
function parseLevelLines(levelLine) {
    for (var i = 0; i < 15; i++) {
        for (var j = 0; j < 20; j++) {
            loadTile(levelLine.charAt((i * 20) + j), j, i);
        }
    }
}
// levelLine là toàn bộ dữ liệu của ma trận

function loadTile(tileType, x, y) {
 switch (tileType) {
  case '.':
   break;
  case '2':
   createTile("BlockA0", x, y);
   break;
                ...
}

function createTile(blockTile, x, y) {
 var blockImg = loader.getResult(blockTile);
 var block = new createjs.Shape();
 block.graphics.beginBitmapFill(blockImg).drawRect(x * 40, y * 32, 40, 32);
 stage.addChild(block);
}

vậy là được 1 bản đồ

ĐỌC BẢN ĐỒ TỪ FILE TXT


/**
* lấy file levels
* 0.txt, 1.txt,...
* mặc định levelIndex = -1
*/
function loadNextLevel() {
 this.levelIndex = (this.levelIndex + 1) % numberOfLevels;

    // Searching where we are currently hosted
    var nextLevelUrl = window.location.href.replace('index.html', '') + "levels/" + this.levelIndex + ".txt";
    try {
        var request = new XMLHttpRequest();
        request.open('GET', nextLevelUrl, true);

        // Little closure
        request.onreadystatechange = function () {
            onLevelReady(this);
        };
        request.send(null);
    }
    catch (e) {
        // Probably an access denied if you try to run from the file:// context
        // Loading the hard coded error level to have at least something to play with
        parseLevelLines(textLevelError);
    }
}

/**
* kiểm tra xem có lấy được file từ server k
* nếu không lây được sẽ tạo maps tỉnh từ code textLevelError
*/
function onLevelReady(eventResult) {
 var newTextLevel = "";

    if (eventResult.readyState == 4) {
        // If everything was OK
        if (eventResult.status == 200)
            newTextLevel = eventResult.responseText.replace(/[\n\r\t]/g, '');
        else {
            console.log('Error', eventResult.statusText);
            // Loading a hard coded level in case of error
            newTextLevel = textLevelError;
        }

        parseLevelLines(newTextLevel);
    }
}

Saturday, January 31, 2015

Canvas database client (sqlite)

database client (Sqlite)


1. Open Database
Phương thức này có nhiệm vụ mở một database có sẵn hoặc tạo mới nếu nó chưa tồn tại. Phương
thức này được khai báo như sau:
Database openDatabase(
in DOMString name,
in DOMString version,
in DOMString displayName,
in unsigned long estimatedSize,
in optional DatabaseCallback creationCallback
);

Tham số:
-      name: tên của database.
-    version: phiên bản. Hai database trùng tên nhưng khác phiên bản thì khác nhau.
-    displayname: mô tả.
-    estimatedSize: dung lượng được tính theo đơn vị byte.
-    creationCallback: phương thứ c callback được thực thi sau khi database mở/tạo.
Ví dụ tạo một database với tên “mydb” và dung lượng là 5 MB:
var db = openDatabase("mydb", "1.0", "My First DB", 5 * 1024 * 1024); 
2. Transaction
Bạn cần thực thi các câu SQL trong ngữ cảnh của một transactio n. Một transaction cung cấp khả
năng rollback khi một trong những câu lệnh bên trong nó thực thi thất bại. Nghĩa là nếu bất kì
một  lệnh SQL  nào thất bại,  mọi  thao tác  thực hiện trước đó trong transaction sẽ bị  hủy bỏ và
database không bị ảnh hưởng gì cả.
Interface  Database  hỗ  trợ  hai  phương  thức  giúp  thực  hiện  điều  này  là  transaction()  và
readTransaction().  Điểm  khác  biệt  giữa  chúng  là  transaction()  hỗ  trợ  read/write,  còn
readTransaction() là read- only. Như vậy sử dụng readTransaction() sẽ cho hiệu suất cao   hơn nếu
như bạn chỉ cần đọc dữ liệu.
void transaction(
in SQLTransac tionCallback callback,
in optional SQLTransactionErrorCallback errorCallback,
in optional SQLVoidCallback  successCallback
);

Ví dụ:
var db = openDatabase("mydb", "1.0", "My First DB", 5 * 1024 * 1024);
db.transaction(function (tx) {
// Using tx object to execute SQL Statements
});
3. Execute SQL
executeSql() là phương thức duy nhất để thực thi một câu lệnh SQL trong Web SQL. Nó đ ược sử
dụng cho cả mục đích đọc và ghi dữ liệu
void executeSql(
in DOMString sqlStatement,
in optional ObjectArray arguments,
in optional SQLStatementCallback  callback,
in optional SQLStatementErrorCallback  errorCallback
);
Ví dụ  1 : tạo bảng Customers và thêm hai dòng dữ liệu vào bảng này.
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS CUSTOMERS(id unique, name)");
tx.executeSql("INSERT INTO CUSTOMERS (id, name) VALUES (1, 'peter')");
tx.executeSql("INSERT INTO CUSTOMERS (id, name) VALUES (2, 'paul')");
});

Tuy nhiên cách thực thi SQL trên không được rõ ràng và có thể bị các vấn đề về bảo mật như
SQL injection. Vì vậy tốt hơn bạn nên để các tham số cần truyền cho câu SQL trong một mảng
và đặt  vào làm tham số thứ 2 của phương thức executeSql(). Các vị trí trong câu SQL chứa tham
số sẽ được thay thế bởi dấu „?‟:
tx.executeSql("INSERT INTO CUSTOMERS (id, name) VALUES (?,?)", [1,"peter"]);
tx.executeSql("INSERT INTO CUSTOMERS (id, name) VALUES (?,?)", [2,"paul"]);

Note: các transaction trên thực thi bất đồng bộ(các dòng lệnh chạy ko theo thứ tự)

code ex

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        color: #222;
        font: 14px Arial;
      }
      
      body a {
        color: #3D5C9D;
        text-decoration: none;
      }
    </style>
    <script>
      var html5rocks = {};
      html5rocks.webdb = {};
      html5rocks.webdb.db = null;
   var test = false;
      
      html5rocks.webdb.open = function() {
        var dbSize = 5 * 1024 * 1024; // 5MB
        html5rocks.webdb.db = openDatabase("Todo", "1.0", "Todo manager", dbSize);
      }
      
      html5rocks.webdb.createTable = function() {
        var db = html5rocks.webdb.db;
        db.transaction(function(tx) {
          tx.executeSql("CREATE TABLE IF NOT EXISTS todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)", []);
        });
      }
      
      html5rocks.webdb.addTodo = function(todoText) {
        var db = html5rocks.webdb.db;
        db.transaction(function(tx){
          var addedOn = new Date();
          tx.executeSql("INSERT INTO todo(todo, added_on) VALUES (?,?)",
              [todoText, addedOn],
              html5rocks.webdb.onSuccess,
              html5rocks.webdb.onError);
         });
      }
      
      html5rocks.webdb.onError = function(tx, e) {
        alert("There has been an error: " + e.message);
      }
      
      html5rocks.webdb.onSuccess = function(tx, r) {
        // re-render the data.
        html5rocks.webdb.getAllTodoItems(loadTodoItems);
  test = true;
      }
      
      
      html5rocks.webdb.getAllTodoItems = function(renderFunc) {
        var db = html5rocks.webdb.db;
        db.transaction(function(tx) {
          tx.executeSql("SELECT * FROM todo", [], renderFunc,
              html5rocks.webdb.onError);
        });
      }
      
      html5rocks.webdb.deleteTodo = function(id) {
        var db = html5rocks.webdb.db;
        db.transaction(function(tx){
          tx.executeSql("DELETE FROM todo WHERE ID=?", [id],
              html5rocks.webdb.onSuccess,
              html5rocks.webdb.onError);
          });
      }
      
      function loadTodoItems(tx, rs) {
        var rowOutput = "";
        var todoItems = document.getElementById("todoItems");
        for (var i=0; i < rs.rows.length; i++) {
          rowOutput += renderTodo(rs.rows.item(i));
        }
      
        todoItems.innerHTML = rowOutput;
  console.log("1");
  if(rs.rows.length == 0){
   test = false;
   html5rocks.webdb.addTodo(111);
  }else{
   test = true;
  }
      }
      
      function renderTodo(row) {
        return "<li>" + row.todo  + " [<a href='javascript:void(0);'  onclick='html5rocks.webdb.deleteTodo(" + row.ID +");'>Delete</a>]</li>";
      }
      
      function init() {
        html5rocks.webdb.open();
        html5rocks.webdb.createTable();
        html5rocks.webdb.getAllTodoItems(loadTodoItems);
  console.log("2");
  /*if(test==true){
    html5rocks.webdb.getAllTodoItems(loadTodoItems);
    console.log("3");
  }*/
  
  console.log("4");
      }
      
      function addTodo() {
        var todo = document.getElementById("todo");
        html5rocks.webdb.addTodo(todo.value);
        todo.value = "";
      }
    </script>
  </head>
  <body onload="init();">
    <ul id="todoItems">
    </ul>
    <form type="post" onsubmit="addTodo(); return false;">
      <input type="text" id="todo" name="todo" placeholder="What do you need to do?" style="width: 200px;" />
      <input type="submit" value="Add Todo Item"/>
    </form>
  </body>
</html>

Canvas image

http://tech.pro/tutorial/1073/html-5-canvas-tutorial-displaying-images
The Canvas element was introduced a few years ago as part of the HTML 5 standard. This element has opened the doors to incredibly dynamic web applications that in the past were only possible using 3rd party plugins like Flash or Java. This tutorial covers a small but important piece of the canvas element - displaying and manipulating images.

Image Source

The most common way to draw images to a canvas element is to use a Javascript Image object. Which image formats are supported is dependent on the browser, however the typical formats (png, jpg, gif, etc) have very good cross-browser support.
The image can either be grabbed from an existing element already in the DOM or a new one can be constructed on demand.

// Grab an image that's already on the page.
var myImage = document.getElementById('myimageid');

// or create a new image.
myImage = new Image();
myImage.src = 'image.png';
In the current version of most canvas-supported browsers, drawing an image that hasn't been fully loaded simply doesn't do anything. This means, however, that if you want the image to show up, you must wait for it to be loaded before drawing it. This can be done by using the Image object's onload function.
// Create an image.
myImage = new Image();
myImage.onload = function() {
  // Draw image.
}
myImage.src = 'image.png';
For the rest of my examples, the source image I'll be using is the following 256x256 gorilla.
Gorilla source
image

Basic Drawing

For the most basic form of drawing images, all that's required is the position (x and y coordinates) of where you'd like to put the image. Images are positioned relative to their top-left corners. With this technique, images are simply displayed at their original size.
drawImage(image, x, y)

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

ctx.drawImage(myImage, 50, 50);
ctx.drawImage(myImage, 125, 125);
ctx.drawImage(myImage, 210, 210);
Basic Canvas Image
Output

Resizing and Scaling

To change the size of the image, an overloaded version of drawImage is used that accepts the desired width and height.
drawImage(image, x, y, width, height)

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

ctx.drawImage(myImage, 50, 50, 100, 100);
ctx.drawImage(myImage, 125, 125, 200, 50);
ctx.drawImage(myImage, 210, 210, 500, 500);
This example demonstrates drawing an image smaller than the source, stretched to a different aspect ratio, and blown up larger than the source.
Canvas Scaled
Images

Slice and Crop

The last variant of drawImage allows you to take a slice out of (or crop) the source image.
drawImage(image, 
  sourceX, 
  sourceY, 
  sourceWidth, 
  sourceHeight, 
  destX, 
  destY, 
  destWidth, 
  destHeight)
There's a lot of parameters there, but basically you're taking a rectangle out of the source image and drawing that rectangle into a destination rectangle somewhere on the canvas.
Canvas Slice
Example
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

ctx.drawImage(myImage, 0, 0, 50, 50, 25, 25, 100, 100);
ctx.drawImage(myImage, 125, 125, 100, 100, 125, 125, 150, 150);
ctx.drawImage(myImage, 80, 80, 100, 100, 250, 250, 220, 220);
Canvas
Slices
That does it for all the basic ways to draw and manipulate images using the HTML 5 canvas. Drawing images is a small part of what the canvas provides, and we'll be posting more tutorials in the future that covers more of this element and its features.