みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

CanvasにPointを打つ

指定した座標に点を打つクラスをつくってみました。
点の色も大きさも選べないシンプルなクラスですが、今後のことを考えてEventDisatcherを継承しています。


JavaScript

(function(win, doc, ns) {

    "use strict";

    function Point(x, y) {
        var _this = this;

        _init();

        function _init() {
            ns.EventDispatcher.call(_this);
        }

        _this.x = x;
        _this.y = y;
    }

    Point.prototype = new ns.EventDispatcher();
    Point.prototype.constructor = Point;

    Point.prototype.draw = function(ctx) {
        var _this = this,
            size  = 5;

        ctx.save();
            ctx.beginPath();
            ctx.arc(_this.x, _this.y, size, 0, Math.PI * 2, false);
            ctx.fill();
            ctx.moveTo(_this.x, _this.y);
        ctx.restore();

        return _this;
    };

    ns.Point = Point;

})(this, document, App);

つかいかた

HTML

<canvas id="canvas"></canvas>

JavaScript

(function(win, doc, ns) {

    "use strict";
    
    var canvas = doc.getElementById("canvas"),
        ctx = canvas.getContext("2d");
    
    canvas.width = win.innerWidth;
    canvas.height = win.innerHeight;
    
    (new ns.Point(100, 100)).draw(ctx);
    (new ns.Point(200, 100)).draw(ctx);
    (new ns.Point(200, 200)).draw(ctx);
    (new ns.Point(300, 200)).draw(ctx);
    (new ns.Point(300, 300)).draw(ctx);
    
})(this, document, App);

DEMO



まずはここからはじめましょう。