LoginSignup
14
21

More than 5 years have passed since last update.

即興で作るHTML5 Canvasを用いたスマホ用お絵かきツール

Posted at

動けばいいという気持ちで作ったので、とても適当です。
テスト用というかお遊び程度に。
動作確認:iOS7

作り方

まずcanvas要素が必要なので書き出します。
大きさは、後に座標を扱う際bodymarginによるズレを軽減するのと、viewport設定を紛らわすために、ある程度大きくします。大体1000くらいでいいでしょう。

<canvas width="1000" height="1000"></canvas>

次にいきなりscriptを書きます。
要素取得してgetContextするあたりまではお決まりです。

var a = document.querySelector("canvas"),
    c = a.getContext("2d");

最後に、touchイベントを書いて終わりです。
beginPathがどうこうとかは省きます。
座標はpageXでもclientXでもscreenXでもなんでもいいです。

a.ontouchstart = function (e) {
  e.preventDefault(); //固定用
  c.moveTo(e.touches[0].pageX, e.touches[0].pageY); //パスをタッチした地点へ
};

a.ontouchmove = function (e) {
  c.lineTo(e.touches[0].pageX, e.touches[0].pageY); //動いたところまで線を引く
  c.stroke(); //描画
};

以上で大体動きます。つなげると以下のようになります。

<canvas width="1000" height="1000"></canvas>

<script>
var a = document.querySelector("canvas"),
    c = a.getContext("2d");

a.ontouchstart = function (e) {
  e.preventDefault();
  c.moveTo(e.touches[0].pageX, e.touches[0].pageY);
};

a.ontouchmove = function (e) {
  c.lineTo(e.touches[0].pageX, e.touches[0].pageY);
  c.stroke();
};

</script>
14
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
21