タッチイベントアプリの作成
touchイベントを使って
スクリーンにタッチして絵を描くペイントソフトをつくる
touchイベントがマルチタッチを捕らえることに注目し
タッチした指で色が変わるようにする
とりあえず、headでは、必要なライブラリーの読み込み
bodyでは画面の作成
<div data-role="page" id="touchpaint"> <div data-role="header"> <h1>タッチイベント</h1> </div> <div data-role="content"> <div id="canvas"></div> </div>
処理はJavascript
//指が増えるごとに色を変化
color = [
'rgb(255,0,0)',
'rgb(0,255,0)',
'rgb(0,0,255)',
'rgb(255,255,0)',
'rgb(255,0,255)'
];
$(document).on("pageshow","#touchpaint",function(){
//html()で動的に追加
$("#canvas").html('<canvas id="drawable" width="'+window.innerWidth+'"height="'+window.innerHeight+'" />');
canvas = $("#drawable")[0];
ctx = canvas.getContext('2d');
//追加領域での操作
$(this).on("touchmove","#drawable",function(e){
ratioX = canvas.height / canvas.clientHeight;
ratioY = canvasWidth / canvas.clientWidth;
//ブラウザーの基本動作無効化
e.preventDefault();
$.each(e.originalEvent.touches, function(idx){
//座標取得
x =(this.pageX - canvas.offsetLeft) * ratioX;
y = (this.pageY - canvas.offsetTop) * ratioY;
//描画
ctx.beginPath();
ctx.fillStyle= color[idx];
ctx.arc(x,y,10, 0* Math.PI / 180, 360 * Math.PI / 180, true);
ctx.fill();
});
});
});
$.each()については
http://qiita.com/YusukeHirao/items/8d1089c2bf86e7dc05ef
の解説がわかりやすいとおもいます
この$.each()は配列を扱う関数
引数には、
配列
コールバック関数
となっている
arc()については
http://www.html5.jp/canvas/ref/method/arc.html
を参考に
構文は
arc(
中心のx座標,
中心のy座標,
半径,
開始地点,
終了地点,
回る向きでtrueなら時計回り
)
となる
つまり
ctx.arc(x,y,10, 0* Math.PI / 180, 360 * Math.PI / 180, true);
なら
ctx.arc(
//x座標
x,
//y座標
y,1
//半径
0,
//開始地点
0* Math.PI / 180,
//終了地点
360 * Math.PI / 180,
//回る向き
true);
となる