tmlib.js에서 체크박스

14771 단어 JavaScripttmlib.js
tmlib.스플릿으로 체크박스를 구현합니다.
그림과 크기는 임의입니다.
생략한 후 이미지 -> 고정 이름으로 지정한 크기 -> ON의 이미지 크기를 검사합니다.
jsdo.it에 샘플을 넣었어요.
/**
 * チェックボックスクラス
 */
var Checkbox = tm.createClass({
    superClass: tm.app.Sprite,

    trueImage: null,
    falseImage: null,
    disabledImage: null,

    disabled: false,
    checked: false,

    init: function(x, y, trueImg, falseImg, disabledImg, width, height) {
        // 画像指定無しなら標準のを指定
        this.trueImage = (trueImg == null) ? "checked" : trueImg;
        this.falseImage = (falseImg == null) ? "nochecked" : falseImg;
        this.disabledImage = (falseImg == null) ? "disablechecked" : disabledImg;

        // チェックボックスのサイズ指定無しならチェックON画像のサイズを使用
        var img = tm.graphics.TextureManager.get(this.trueImage);
        if (width == null) { width = img.width; }
        if (height == null) { height = img.height; }
        this.superInit(width, height);
        this.setPosition(x, y);

        // マウスイベントを有効化
        this.interaction.enabled = true;
        this.interaction.boundingType = "rect";
    },

    update: function() {
        this.setCheckImage();
    },

    // チェック切り替え
    onpointingend: function() {
        if (this.disabled) return;
        this.checked = !this.checked;
    },

    // イメージの切り替え
    setCheckImage: function() {
        if (this.disabled) {
            this.image = this.disabledImage;
            return;
        }
        this.image = this.checked ? this.trueImage : this.falseImage;
    },

    setDisabled: function(stat) {
        this.disabled = stat;
    },

    setChecked: function(stat) {
        this.checked = stat;
    },
});
예제 사용(Checkbox 클래스 정의 생략)
/*
 * constant
 */
var SCREEN_WIDTH    = 640;
var SCREEN_HEIGHT   = 920;
var SCREEN_CENTER_X = SCREEN_WIDTH / 2;
var SCREEN_CENTER_Y = SCREEN_HEIGHT / 2;

// 画像のプリロード
tm.preload(function(){
    tm.graphics.TextureManager.add("checked", "checked.png");
    tm.graphics.TextureManager.add("nochecked", "nochecked.png");
    tm.graphics.TextureManager.add("disablechecked", "disablechecked.png");
});

/*
 * メイン処理(ページ読み込み後に実行される)
 */
tm.main(function() {

    // アプリケーション作成
    var app = tm.app.CanvasApp("#world");
    app.resize(SCREEN_WIDTH, SCREEN_HEIGHT); // リサイズ
    app.fitWindow();    // 自動フィット
    app.background = "white";

    // シーンを切り替える
    app.replaceScene(MainScene());

    // 実行
    app.run();
});


tm.define("MainScene", {
    superClass: "tm.app.Scene",

    init: function() {
        // 親の初期化
        this.superInit();

        // チェックボックスの表示
        Checkbox(300, 40).addChildTo(this);                      // nocheck
        Checkbox(300, 110).addChildTo(this).setChecked(true);    // checked
        Checkbox(300, 180).addChildTo(this).setDisabled(true);   // disable
    },
});
이렇게 돼서

좋은 웹페이지 즐겨찾기