cocos2d-js

cocos-js Http方式網(wǎng)絡(luò)請(qǐng)求
JavaScript秘密花園
廖雪峰的官方網(wǎng)站
文檔參考
動(dòng)作列表
Node.js
node.js怎么判斷當(dāng)前是mac系統(tǒng)還是windows系統(tǒng)
【Cocos2d-x】實(shí)現(xiàn)可上下左右無(wú)限滾動(dòng)的背景
Node.js v8.9.3 文檔

顏色

// 定義
static const Color3B WHITE;
static const Color3B YELLOW;
static const Color3B BLUE;
static const Color3B GREEN;
static const Color3B RED;
static const Color3B MAGENTA;
static const Color3B BLACK;
static const Color3B ORANGE;
static const Color3B GRAY;

/* 使用方式 */

// 預(yù)設(shè)顏色
cc.color.WHITE;

/*
 * 自定義顏色
 * @param R 紅色取值,0~255
 * @param G 紅色取值,0~255
 * @param B 紅色取值,0~255
 * @param A 顏色透明度,0~255,可不傳(默認(rèn)255)
 */
cc.color(R,G,B,A); 

/*
 * 十六進(jìn)制顏色值
 */
cc.hexToColor("#FFD751")

Layout

// 初始化
var bg_layout = new ccui.Layout();

// 設(shè)置大小
bg_layout.setSize(1280, 720);

// 設(shè)置位置
bg_layout.setPosition(0, 0);

/*
 * 設(shè)置圖層背景色填充類(lèi)型
 * void setBackGroundColorType(BackGroundColorType type);
 * @param type NONE——無(wú)填充色 SOLID——純色背景 GRADIENT——漸變色
 */
bg_layout.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID);

/*
 * 設(shè)置圖層背景色(要與setBackGroundColorType配合使用)
 * void setBackGroundColor(const Color3B &color); 純色背景
 * void setBackGroundColor(const Color3B &startColor, const Color3B &endColor); 漸變色背景
 * @param color 背景色
 * @param startColor 漸變色開(kāi)始顏色
 * @param endColor 漸變色結(jié)束顏色
 */
bg_layout.setBackGroundColor(cc.color.WHITE);

/*
 * 設(shè)置圖層背景色透明度 
 * @param opacity 透明度0~255
 */
bg_layout.setBackGroundColorOpacity(160);

/*
 * 設(shè)置背景圖
 * void setBackGroundImage(const std::string& fileName,TextureResType texType = TextureResType::LOCAL);
 * @param fileName 圖片地址
 * @param texType 圖片來(lái)源: 0——本地 1——plist
 */
bg_layout.setBackGroundImage("abc.png", ccui.Widget.PLIST_TEXTURE);

/*
 * 九宮格渲染圖片
 */
void setBackGroundImageScale9Enabled(bool enabled);

TableView(列表)

參考:
Cocos2d-lua示例(一)排行榜之TableView
cocos2d-x CCTableView動(dòng)態(tài)插入刪除元素bug修正及動(dòng)畫(huà)表現(xiàn)

/**
 * TableView初始化
 * @param dataSource 數(shù)據(jù)源
 * @param size       視圖大小
 */
static TableView* create(TableViewDataSource* dataSource, Size size);

// 初始化
this._tableView = new cc.TableView(this, cc.size(200, 500));

// 設(shè)置滾動(dòng)方向
// cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0;
// cc.SCROLLVIEW_DIRECTION_VERTICAL = 1;
this._tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);

// 添加交互
this._tableView.setTouchEnabled(true);

// 設(shè)置錨點(diǎn)
this._tableView.setAnchorPoint(0, 5);

// 位置
this._tableView.setPosition(170, 640);
// this._tableView.x = 0;  
// this._tableView.y = 0;  

// 設(shè)置委托  
this._tableView.setDelegate(this);  

// 刷新列表
this._tableView.reloadData();

// tableView填充方式 (如果數(shù)組是[1, 2, 3],那么使用TABLEVIEW_FILL_BOTTOMUP會(huì)展示3,2,1由上向下)
// cc.TABLEVIEW_FILL_TOPDOWN = 0; 由上往下排序
// cc.TABLEVIEW_FILL_BOTTOMUP = 1; 又下往上排序
this._tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);  

/**
 * 設(shè)置cell個(gè)數(shù)
 * @paramer table 列表
 */
numberOfCellsInTableView: function (table) {  
    return 20; 
},  

/**
 * 添加Cell   
 * @paramer table 列表
 * @paramer idx   索引
 */
tableCellAtIndex: function (table, idx) {  
    var cell = table.dequeueCell();
    // var item = this._listArray[idx];   

    if (!cell) {  
        cell = new CustomTableViewCell();    
    }else{
        cell.removeAllChildren();
    }
  
    var _tip_txt = new cc.LabelTTF("", "Arial", 20,cc.size(550, 125),0,cc.VERTICAL_TEXT_ALIGNMENT_CENTER); 
    cell.addChild(_tip_txt);

    return cell;  
}, 

/**
 * 設(shè)置點(diǎn)擊cell后的回調(diào)函數(shù)  
 * @paramer table 列表
 * @paramer cell  行
 */
tableCellTouched: function (table, cell) {  
    // cell的下標(biāo)
    var index = cell.getIdx();
},  

/**
 * 設(shè)置cell大小  
 * @paramer table 列表
 * @paramer idx   索引
 */
tableCellSizeForIndex: function (table, idx) {  
    return cc.size(600, 60);  
},   

/**
 * 交互事件
 * @paramer sender 
 * @paramer type 
 */
touchEvent: function (sender, type) {  
    if (type == ccui.Widget.TOUCH_ENDED) {
        
    }
},

var CustomTableViewCell = cc.TableViewCell.extend({  
    draw: function (ctx) {  
        this._super(ctx);  
    }  
});

// 問(wèn)題解決:點(diǎn)擊列表cell的時(shí)候,如果直接執(zhí)行界面轉(zhuǎn)換會(huì)導(dǎo)致tableView被釋放,被釋放的tableView會(huì)執(zhí)行onTouchEnded方法,從而導(dǎo)致應(yīng)用崩潰。
// 執(zhí)行延遲跳轉(zhuǎn),可以讓tableView將剩余的方法調(diào)用完才進(jìn)行跳轉(zhuǎn),解決崩潰。
setTimeout(function () {
  game.Proceduar.switch(game.proceduar.MyNiuCircle);        
}.bind(this), 30); 

RichText(富文本)

// 初始化  
var richText    = new ccui.RichText();      

// 忽略?xún)?nèi)容自適應(yīng)
richText.ignoreContentAdaptWithSize(false);

// 設(shè)置位置
richText.setPosition(this.width / 2, 520);

// 寬高
richText.width = 340;
richText.height = 46;

// 三種元素分別是文字、圖片、普通節(jié)點(diǎn)(用普通節(jié)點(diǎn)就可以掛從Node派生的類(lèi))。
// tag貌似內(nèi)部沒(méi)有用,外部也訪問(wèn)不了,其他參數(shù)容易理解。
static RichElementText* create(int tag, const Color3B& color, GLubyte opacity, const std::string& text, const std::string& fontName, float fontSize);  
static RichElementImage* create(int tag, const Color3B& color, GLubyte opacity, const std::string& filePath);  
static RichElementCustomNode* create(int tag, const Color3B& color, GLubyte opacity, Node* customNode);  

// 創(chuàng)建樣式
var re1 = new ccui.RichElementText(1, cc.color.WHITE, 255, '這是白色白色白色白色白色白色', '黑體', 24);  
var re2 = new ccui.RichElementText(2, cc.color.RED, 255, '這是紅色紅色紅色紅色紅色紅色紅色', '楷體', 24);  
var reimg = new ccui.RichElementImage(3, cc.color.WHITE, 255, 'res/pic/CloseNormal.png');  
var renode = new ccui.RichElementCustomNode(4, cc.color.WHITE, 255, new cc.Sprite('res/pic/CloseNormal.png'));  

// 增刪元素
void insertElement(RichElement* element, int index);  
void pushBackElement(RichElement* element);  
void removeElement(int index);  
void removeElement(RichElement* element);    

// 添加樣式
richText.pushBackElement(re1);
richText.pushBackElement(re2);
richText.pushBackElement(reimg);
richText.pushBackElement  (renode);

// 添加到界面
this.addChild(richText);
富文本

EditBox(輸入框,可自動(dòng)將界面上移)

// 初始化
textfield = new cc.EditBox(cc.size(100, 100), new cc.Scale9Sprite(""))
// 控件名
textfield.setName("");

// 設(shè)置錨點(diǎn)
textfield.setAnchorPoint(0, 0);

// 設(shè)置位置
textfield.setPosition(0, 0);

// 設(shè)置代理
textfield.setDelegate(this);

// 最大長(zhǎng)度
textfield.setMaxLength(100);

// 占位符
textfield.setPlaceHolder("輸入聊天內(nèi)容");

// 占位符字體色
textfield.setPlaceholderFontColor(cc.color(53,53,53)) 

// 字體色
textfield.setFontColor(cc.color(53,53,53))

//修改為不使用密文
textfield.setInputFlag(cc.EDITBOX_INPUT_FLAG_SENSITIVE);    

//設(shè)置不可換行,可以輸入任意文字
textfield.setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);   

this.addChild(this._chatTextField);


// 返回鍵類(lèi)型
cc.KEYBOARD_RETURNTYPE_DEFAULT = 0;    // 默認(rèn)
cc.KEYBOARD_RETURNTYPE_DONE = 1;       // 完成
cc.KEYBOARD_RETURNTYPE_SEND = 2;       // 發(fā)送
cc.KEYBOARD_RETURNTYPE_SEARCH = 3 ;    // 搜索
cc.KEYBOARD_RETURNTYPE_GO = 4;         // 前往

// 輸入鍵盤(pán)類(lèi)型
cc.EDITBOX_INPUT_MODE_ANY = 0;          // 任何類(lèi)型
cc.EDITBOX_INPUT_MODE_EMAILADDR = 1;    // 允許用戶(hù)輸入電子郵件地址
cc.EDITBOX_INPUT_MODE_NUMERIC = 2;      // 允許用戶(hù)輸入一個(gè)整數(shù)值。
cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3;  // 允許用戶(hù)輸入電話號(hào)碼
cc.EDITBOX_INPUT_MODE_URL = 4;          // 允許用戶(hù)輸入一個(gè)URL。
cc.EDITBOX_INPUT_MODE_DECIMAL = 5;      // 允許用戶(hù)輸入實(shí)數(shù)值,允許小數(shù)點(diǎn)擴(kuò)展
cc.EDITBOX_INPUT_MODE_SINGLELINE = 6;   // 允許用戶(hù)輸入任何文字,除了換行符。

// 輸入框上的文字
cc.EDITBOX_INPUT_FLAG_PASSWORD = 0;                     // 表示輸入的文本是應(yīng)該是的機(jī)密數(shù)據(jù)
cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1;                    // 表示輸入的文本是敏感數(shù)據(jù)
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2;            // 這個(gè)標(biāo)志是一個(gè)提示,在文本編輯過(guò)程中
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3;        // 這個(gè)標(biāo)志是一個(gè)提示,在文本編輯過(guò)程中
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4;  // 自動(dòng)大寫(xiě)所有字符

Button

// 初始化,參數(shù)分別是默認(rèn)狀態(tài)、按下?tīng)顟B(tài)、禁用狀態(tài)下的圖片
var button = new ccui.Button("", "", "");  

// 錨點(diǎn)
button.setAnchorPoint(0.5, 0.5);

// 設(shè)置圖片(正常情況下的圖片、點(diǎn)擊時(shí)的圖片、禁用時(shí)的圖片)
button.loadTextures("res/a.png", "res/b.png", "res/c.png");

// 位置
button.setPosition(10, 10);  

// 設(shè)置是否伴隨點(diǎn)擊縮放按鈕圖片  
emojiBtn.setPressedActionEnabled(false);

// 按鈕標(biāo)題
button.setTitleText(emojiList[i]);

// 按鈕標(biāo)題大小
button.setTitleFontSize(40);

// 按鈕標(biāo)題顏色 兩者相同
button.setTitleColor(cc.color(53,53,53))
button.setColor(cc.color(0, 0, 0, 255));

// 設(shè)置字體樣式
button.setTitleFontName("宋體,微軟雅黑");

// 允許按鈕穿透(解決在tableView上無(wú)法滾動(dòng)的問(wèn)題)
button.setSwallowTouches(false);

this.addChild(button);

// 透明按鈕(先設(shè)置圖片,然后再調(diào)用loadTextures,參數(shù)傳入"")
var copy_button = new ccui.Button(this.btn_back_img, this.btn_back_img, "", 1);
copy_button.loadTextures("", "", "");

延時(shí)調(diào)用

// 每三秒調(diào)用一次
var interval = setInterval(function () {

}.bind(this), 1000 * 3);

// 結(jié)束定時(shí)調(diào)用
clearInterval(interval);

// 三秒后調(diào)用,僅調(diào)用一次
setTimeout(function(){

}.bind(this), 1000 * 3);

LayerColor(顏色圖層)

var layer = new cc.LayerColor(cc.color(52,52,52,120));
this.addChild(layer); 

Slider(可以做成進(jìn)度條)

var loadingBar = new ccui.Slider();

// 設(shè)置slider背景圖片  
loadingBar.loadBarTexture("res/Circle/Circle_Hongbao/17.png");  
                  
// 設(shè)置slider進(jìn)度圖片  
loadingBar.loadProgressBarTexture("res/Circle/Circle_Hongbao/17.png"); 

// 設(shè)置slider滑動(dòng)按鈕圖片  
// 參數(shù):1. 正常狀態(tài)下的紋理貼圖 2.被選中狀態(tài)下的紋理貼圖 3.禁用狀態(tài)下的紋理貼圖  
loadingBar.loadSlidBallTextures("res/4.png", "res/4.png" ,"res/4.png"); 
loadingBar.setAnchorPoint(0, 0);
loadingBar.setPosition(currentX + 10, currentY);

// 設(shè)置進(jìn)度0~100
loadingBar.setPercent(100);

// 視圖旋轉(zhuǎn)角度
loadingBar.rotation = angle;
this.addChild(loadingBar);

旋轉(zhuǎn)動(dòng)畫(huà)/抖動(dòng)動(dòng)畫(huà)

var hongbaoAnimation = {
    // 抖動(dòng)時(shí)間
    duration:0,

    // 已抖動(dòng)時(shí)間
    dtCost:0.0,

    // X軸抖動(dòng)范圍
    shakeStrengthX:0,
    shakeStrengthY:0,

    // 抖動(dòng)節(jié)點(diǎn)
    shakeNode :null,

    // 抖動(dòng)節(jié)點(diǎn)初始位置
    nodeInitialPos :null,
    
    // 定時(shí)器綁定回調(diào)
    bindCallback :null,
    
    // 定時(shí)器唯一鍵(WEB)
    key :null,

    pause:false,

    /**
     * 自定義抖動(dòng)效果,用于WEB和JSB環(huán)境
     * @param {float}duration 抖動(dòng)時(shí)間
     * @param {number}shakeStrengthX X軸抖動(dòng)幅度
     * @param {number}shakeStrengthY Y軸抖動(dòng)幅度
     * @param {cc.Node}shakeNode 抖動(dòng)節(jié)點(diǎn)
     * @param {string}key 唯一key(WEB環(huán)境)
     * @example:
     * var shakeAction = new Shake2(0.5,20,20,node,"shakeKey");
     * shakeAction.shake();
     */
    startAnimation:function(duration, shakeStrengthX, shakeStrengthY, shakeNode, key) {
        this.duration = duration;
        this.shakeStrengthX = shakeStrengthX;
        this.shakeStrengthY = shakeStrengthY;
        this.shakeNode = shakeNode;
        this.nodeInitialPos = shakeNode.getPosition();
        this.key = key;
        this.shake();
    },

    stopAnimation:function(shakeNode) {
        this.shakeNode = shakeNode;
        this.shakeNode.unscheduleUpdate();
        this.shakeNode.unscheduleAllCallbacks();
        this.shakeNode.rotation = 0;
    },

    shake:function() {
        this.bindCallback = this.doSchedule.bind(this);
        this.shakeNode.unschedule(this.bindCallback);
        if(cc.sys.isNative){
            this.shakeNode.schedule(this.bindCallback, 0.1, cc.REPEAT_FOREVER, 0.5);
        }else{
            this.shakeNode.schedule(this.bindCallback, 0.1, cc.REPEAT_FOREVER, 0.5, this.key);
        }   
    },

    doSchedule:function(dt) {
        if (!this.pause) {
            var dt2 = dt * 50;
            var randX = this.getRandomStrength(-this.shakeStrengthX,this.shakeStrengthX);
            var randY = this.getRandomStrength(-this.shakeStrengthY,this.shakeStrengthY);
            // this.shakeNode.setPosition(cc.pAdd(this.nodeInitialPos,cc.p(randX,randY)));
            this.shakeNode.rotation = randX;
            this.dtCost = this.dtCost + parseFloat(parseFloat(dt).toFixed(2));
        }
    
        if(this.dtCost >= this.duration){
            this.pause = true;
            this.dtCost = 0;
            // this.shakeNode.unschedule(this.bindCallback);
            // this.shakeNode.setPosition(this.nodeInitialPos);
            this.shakeNode.rotation = 0;
            setTimeout(function(){
                cc.log("進(jìn)來(lái)了");
                this.pause = false;
            }.bind(this), 1000 * 2);
        }
    },

    // 獲取兩個(gè)數(shù)間的隨機(jī)值
    getRandomStrength:function(min,max) {
        return Math.random()*(max-min+1)+min;
    },
};

// 使用
var view = ...; // 要旋轉(zhuǎn)的視圖

// 開(kāi)始動(dòng)畫(huà)
hongbaoAnimation.startAnimation(1, 10, 3, view, "shakeKey");

// 結(jié)束動(dòng)畫(huà)
hongbaoAnimation.stopAnimation(view);

左右抖動(dòng)動(dòng)畫(huà)

/**
 * 抖動(dòng)紅包
 * @param  node 要旋轉(zhuǎn)的視圖
 * @param  angle 角度 缺省10度擺動(dòng)
 */
game.ui.shake = function(node, angle){
    this.shake = true;

    // 開(kāi)始抖動(dòng)動(dòng)畫(huà)
    this.action = cc.sequence(
        // 第一個(gè)參數(shù):秒,第二個(gè)參數(shù):繞x軸轉(zhuǎn)動(dòng), 第三個(gè)參數(shù):繞y軸轉(zhuǎn)動(dòng)
        cc.rotateBy(0.2, -10||(-angle),-10||(-angle)),
        cc.rotateBy(0.2, 20||2*angle,20||2*angle),
        cc.rotateBy(0.2, -20||(-2*angle),-20||(-2*angle)),
        cc.rotateBy(0.2, 10||angle,10||angle),
        cc.delayTime(0.7)
    );

    this.action.setTag(1717);
   
    // 開(kāi)始執(zhí)行動(dòng)畫(huà)
    node.runAction(this.action.repeatForever());

    /**
     * 停止抖動(dòng)動(dòng)畫(huà)
     * @param restore 是否恢復(fù)到原來(lái)的角度
     */
    this.stop = function(restore){
        if(this.shake)
            node.stopAction(this.action);
            if (restore) {
                node.rotation = 0;
            }
        this.shake = false;

    };
};

// 需要旋轉(zhuǎn)的視圖
var view = game.findUI(node, "view");

// 初始化一個(gè)旋轉(zhuǎn)控制對(duì)象
this.shake = new game.ui.shake(view);

// 停止
this.shake.stop(true);

LabelTTF(自動(dòng)換行)

/**
 * LabelTTF初始化
 * @param text         文本文本內(nèi)容
 * @param fontFilePath ttf字體文件
 * @param fontSize     字體大小 
 * @param dimensions   控件大小
 * @param hAlignment   文本橫向?qū)R方式 
 *   cc.TEXT_ALIGNMENT_CENTER -- 居中對(duì)齊
 *   cc.TEXT_ALIGNMENT_RIGHT  -- 居右對(duì)齊
 *   cc.TEXT_ALIGNMENT_LEFT   -- 居左對(duì)齊
 * @param vAlignment   文本縱向?qū)R方式
 *   cc.VERTICAL_TEXT_ALIGNMENT_TOP,    -- 頂部對(duì)齊  
 *   cc.VERTICAL_TEXT_ALIGNMENT_CENTER, -- 居中對(duì)齊  
 *   cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM, -- 底部對(duì)齊 
 */
static Label * createWithTTF(const std::string& text, 
                             const std::string& fontFilePath, 
                             float fontSize,
                             const Size& dimensions = Size::ZERO, 
                             TextHAlignment hAlignment = TextHAlignment::LEFT,
                             TextVAlignment vAlignment = TextVAlignment::TOP);

// 初始化
var txt = new cc.LabelTTF("", "Arial", 20,cc.size(550, 125),0,cc.VERTICAL_TEXT_ALIGNMENT_CENTER); 
// 設(shè)置位置
txt.setPosition(640,200); 
// 視圖大小
txt.setDimensions(100, 100);
// 設(shè)置字體顏色
txt.color = cc.color(252, 211, 84, 255);  
// 設(shè)置內(nèi)容
txt.setString("內(nèi)容");
// 文字大小
txt.setFontSize(100);
// 文字對(duì)齊 
// cc.TEXT_ALIGNMENT_LEFT; 
// cc.TEXT_ALIGNMENT_RIGHT;
txt.textAlign = cc.TEXT_ALIGNMENT_CENTER;
txt.setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
txt.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);

// 文字顯示范圍
txt.setDimensions(width, height); 
// 忽略anchor的設(shè)置
txt.ignoreAnchor = true; // 設(shè)置后,label的起始點(diǎn)在左下角
// 添加到圖層
this.addChild(txt); 

// 文字定義:
var text = new cc.LabelTTF(“文字”, def);

// def 是這樣定義:
var def = new cc.FontDefinition(); // 聲明文字定義
def.fontName = "STYuanti-SC-Regular"; // 字體
def.fontSize = 20; // 字號(hào)大小
def.alignment = cc.TEXT_ALIGNMENT_CENTER; // 文字對(duì)齊
def.vertAlignment = cc.VERTICAL_TEXT_ALIGNMENT_CENTER;
def.fillStyle = cc.color("#FFFFFF"); // 字體(內(nèi)部)顏色
def.strokeEnabled = true; // 開(kāi)啟文字描邊效果
def.strokeStyle = cc.color("#535D39"); // 描邊的顏色
def.lineWidth = 3; // 字體的寬度
def.shadowEnabled = true; // 開(kāi)啟陰影效果
def.shadowOffsetX = 12; // 陰影X軸效果
def.shadowOffsetY = 12; // 陰影Y軸效果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容