Flashを使っていた方にはわかりやすいと評判のJavaScriptライブラリ、CreateJSを使ってみています。
ゲームらしいものを作りたいのですが、とりあえずはそこに至るまでいろいろやる必要があるかな~ということでテストしてみました。まずは簡単にデジタル時計でも…ということでこんなのを作ってみました。
時計の背景の色は毎秒ColorMatrixFilterで変えています。
ソースはメイン部分を抜粋すると以下の様な感じです。
var SPFD = SPFD || {};
(function(){
var _stage;
var _baseShape;
var _txt;
var _hue = 0;
init = function(){
initStage();
drawWatch();
},
initStage = function(){
var el = $("#stage").get(0);
_stage = new createjs.Stage(el);
_stage.width = el.width;
_stage.height = el.height;
},
drawWatch = function(){
var watchContainer = new createjs.Container();
var baseShape = new createjs.Shape();
baseShape.width = 330;
baseShape.height = 120;
var g = baseShape.graphics;
g.beginFill("#E0EAA3");
g.setStrokeStyle(10);
g.beginStroke("#B5B4B4");
g.drawRoundRect(0, 0, baseShape.width, baseShape.height, 10);
g.endFill();
var dispShape = new createjs.Shape();
dispShape.width = 270;
dispShape.height = 60;
g = dispShape.graphics;
g.beginFill("#D8D8D8");
g.setStrokeStyle(10);
g.beginStroke("#5A5A5A");
g.drawRoundRect(0, 0, dispShape.width, dispShape.height, 10);
g.endFill();
dispShape.x = (baseShape.width - dispShape.width) / 2;
dispShape.y = (baseShape.height - dispShape.height) / 2;
var txt = new createjs.Text("00:00 00", "30px 'Press Start 2P'", "#000000");
txt.textAlign = "center";
txt.x = dispShape.x + dispShape.width / 2;
txt.y = dispShape.y + 15;
_baseShape = baseShape;
_txt = txt;
watchContainer.addChild(baseShape);
watchContainer.addChild(dispShape);
watchContainer.addChild(txt);
_stage.addChild(watchContainer);
watchContainer.x = 10;
watchContainer.y = 10;
setTime();
_stage.update();
setInterval(loop, 1000);
},
setTime = function(){
var date = new Date();
var h = get2digit(date.getHours());
var m = get2digit(date.getMinutes());
var s = get2digit(date.getSeconds());
_txt.text = h + ":" + m + ":" + s;
},
setFilter = function(){
var cmtx = new createjs.ColorMatrix(0, 0, 0, _hue);
var cmf = new createjs.ColorMatrixFilter(cmtx);
_baseShape.filters = [cmf];
_baseShape.cache(-5, -5, _baseShape.width + 10, _baseShape.height + 10);
_hue += 10;
if(_hue >= 180){
_hue -= 360;
}
},
loop = function(){
setTime();
setFilter();
_stage.update();
},
get2digit = function(num){
return (num < 10) ? '0' + num : num;
};
SPFD.init = init;
})();
その場でShapeを描画しているので、大分長いですが、やってることは単純です。CreateJS本体は公式のCDN(全部含む版)を使っています。フォントの「Press Start 2P」はGoogleWebFontsです。日本語は入っていませんが、ゲームっぽいドットフォントで素敵です。
Filter関連はCreateJS本体には含まれていないので、別途DLする必要がありました。githubでEaselJS全部入りのzipをDLして、src/easeljs/filtersから抜き取ったら楽でした。
このくらいだったらHTMLやったほうが早いような気もしますね…。次はもうちょっとゲームっぽいものを作れたらいいかなと思います。
参考:FN1209003 – EaselJSのフィルタColorMatrixFilterでイメージをセピア調に変える – HTML5 : テクニカルノート
