アットウィキロゴ

ゲームブックでは、何十回も何百回もサイコロを振る必要があります。 Web上でサイコロを振れるようにしましょう。そしてユーザーがサイコロをクリックしたらサイコロが止まる。 まずはサイコロを描くことから。 画像ファイルを読み込んでもいいのだけど、ファイルをhtmlの1個だけにしたかったので、canvas機能を試してみた。

ここら辺の知識は 「HTML5 CanvasでつくるRPG 」から仕入れました。

<canvas id="dice_canvas" width="500" height="210" onclick="dice.stop()" style="background: #ccffcc;"></canvas>
<!-- Script の前にcanvasの宣言 -->

<script>

var cv = document.getElementById("dice_canvas"); // IDを頼りにcanvasオブジェクトを取得
var ctx = cv.getContext("2d"); // 2Dモードを指定

// サイコロの1の目を描く。
// 引数は center_xとcenter_yがサイコロの中心のxとy座標
function draw_pip1(center_x, center_y) { 
//DRAW 1
    // 背景の四角を描く
    ctx.fillStyle = 'rgb(255, 255, 255)'; // 塗りつぶしは白
    ctx.strokeStyle = 'rgb(  0,   0,   0)'; // 輪郭は黒
    ctx.beginPath();
   // 白の塗りつぶしの四角を描く。引数は、左上角のx座標、左上角のy座標、横幅、縦高
    ctx.fillRect(center_x - 80, center_y - 80, 80 * 2, 80 * 2);      //ctx.fillRect(x, y, width, height)
   // 外枠の黒の四角を描く。引数は、左上角のx座標、左上角のy座標、横幅、縦高
    ctx.strokeRect(center_x - 80, center_y - 80, 80 * 2, 80 * 2);      //ctx.fillRect(x, y, width, height)

    // 1の赤の目を描く
    ctx.fillStyle = 'rgb(255,   0,   0)'; // 塗りつぶしは赤
    ctx.storkeStyle = 'rgb(255,   0,   0)'; // 輪郭は赤
    ctx.beginPath();
    // cxt.arc(中心のx座標、中心のy座標、直径、始角ラジアン、終角ラジアン、反時計回り)
    ctx.arc(center_x, center_y, 16 * 2, 0, Math.PI * 2, true);
    ctx.fill(); // 塗りつぶし
}

draw_pip1(150, 105);

一度に振るサイコロの数の上限は3個にしたかった。でも普段使うサイコロの個数は2個。なので、2個で見栄えが良く、3個でぎゅうぎゅうなレイアウトにしました。

タグ:

+ タグ編集
  • タグ:
最終更新:2012年04月01日 17:37