Cocos Creator 實現畫板(你畫我猜)

前言

本例是基於cocos官方推薦raphael實現的。其中畫板與看板的同步處理我採用的是在畫板畫完一條線以後看板再同步數據來顯示畫線過程。javascript

1、實現效果以下:

2、畫板核心代碼

一、初始化畫板參數html

onLoad: function () {

        // 初始化參數
        this.lineWidth = 5;
        this.strokeColor = cc.color(0, 0, 0);
        this.isClearMode = false;
        this.group = this.addComponent('R.group');

        // 綁定觸摸通知事件通知
        cc.eventManager.addListener({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            onTouchBegan: this.onTouchBegan.bind(this),
            onTouchMoved: this.onTouchMoved.bind(this),
            onTouchEnded: this.onTouchEnded.bind(this),
        }, this.node);
    },複製代碼

須要注意的事項:java

① 本例使用的是 raphael 庫的 group 的概念來處理的畫板中的線node

二、觸摸開始事件回調處理git

onTouchBegan: function (touch, event) {

        // 初始一條線的數據
        this.dataDict = {};
        this.dataDict.dataEvent = 'draw';

        // 獲取開始時間點
        this.dataDict.startTime = new Date().getTime();

        // 獲取觸摸點數據
        var touchLoc = touch.getLocation();
        touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);

        // 從group獲取一條Path實例
        var path = this.group.addPath();
        path.fillColor = 'none';

        // 判斷是不是橡皮擦狀態
        if (this.isClearMode) {

            path.lineWidth = 15;
            path.strokeColor = cc.color(255, 255, 255);
        } else {

            path.lineWidth = this.lineWidth;
            path.strokeColor = this.strokeColor;
        }

        this.dataDict.strokeColor = path.strokeColor.toHEX("#rrggbb");
        this.dataDict.lineWidth = path.lineWidth;

        // 初始化點數組,並賦值開始位置的點
        this.points = [touchLoc];

        return true;
    },複製代碼

須要注意的事項:github

① 橡皮擦處理的方式是用與畫板背景色相同的顏色畫線,並加粗線的寬度來實現的。web

this.dataDict 記錄的數據是爲了經過 webSocket 傳遞到看板,來使看板同步畫線。npm

三、觸摸移動事件處理數組

onTouchMoved: function (touch, event) {

        // 獲取觸摸點數據
        var touchLoc = touch.getLocation();
        touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);

        // 添加到點數組內
        this.points.push(touchLoc);

        // 獲取當前畫的path實例,並更新內部展示點數據
        var path = this.group.children[this.group.children.length - 1];
        path.points(this.points);
    },複製代碼

須要注意的事項:服務器

① 每次獲取的都是group中最新的一條path去畫。

四、觸摸事件結束處理

onTouchEnded: function(touch, event) {

        // 獲取觸摸點數據
        var path = this.group.children[this.group.children.length - 1];
        path.points(this.points);

        // 獲取結束時間點
        this.dataDict.endTime = new Date().getTime();

        // 將點數組轉化爲相對於node寬高的映射位置
        this.pointDicts = [];
        for (var i = 0; i < this.points.length; i++) {

            let point = this.points[i];
            var pointDict = {};
            pointDict.x = point.x / this.node.width;
            pointDict.y = point.y / this.node.height;
            this.pointDicts.push(pointDict);
        }
        this.dataDict.points = this.pointDicts;

        let sendData = this.dataDict;

        // 本地測試同步數據
        // this.lookDraw.startDraw(sendData);

        // 網絡同步數據
        if (window.room_user) {

            var drawAction = gameAction.getDrawDataAction(window.room_user, sendData)
            happySocket.sendData(drawAction)

        }

    },複製代碼

須要注意的事項:

① 首先爲了適應不一樣的屏幕,須要獲取到實際畫點的相對於寬高的映射點。

② 本地測試與網絡同步數據可根據本身項目作相應的處理。

③ 也可在本地搭建webSocket去模擬實際服務器傳輸,能夠看這裏

四、其餘處理(好比清屏、橡皮擦)

// 清屏
    clearAll: function() {

        this.group.ctx.clear();
        this.group.children = [];
        this.isClearMode = false;

        // 初始化清屏的數據
        this.dataDict = {};
        this.dataDict.dataEvent = 'clear';
        let sendData = this.dataDict;

        // 本地測試同步數據
        // this.lookDraw.startDraw(sendData);

        // 網絡同步數據
        if (window.room_user) {

            var drawAction = gameAction.getDrawDataAction(window.room_user, sendData)
            happySocket.sendData(drawAction)

        }
    },

    // 橡皮擦
    rubber: function() {

        this.isClearMode = true;
    },複製代碼

須要注意的事項:

① 清屏的action會放入看板事件隊列中,在畫完最後一條線後執行。具體看看板代碼。

3、看板核心代碼

一、初始化參數(要與畫板保持一致)

onLoad: function () {

        // 初始化數據
        this.lineWidth = 5;
        this.strokeColor = cc.color(0, 0, 0);
        this.isClearMode = false;
        this.group = this.addComponent('R.group');
        this.time = 3.0;
        this.duration = 1.0;
        this.pathArray = [];

        // 監聽畫板數據
        happyDispatch.addEventListener('happyAction', this.receiveData, this);

    },複製代碼

須要注意的事項:

this.pathArray 爲畫線的事件隊列。

二、開始畫線

// 開始畫線
    startDraw: function (dataDict) {
        // 判斷是不是清屏
        if (dataDict.dataEvent === 'clear') {

            this.pathArray.push(dataDict);
            return;
        }

        // 初始化線
        let path = this.group.addPath();
        path.strokeColor = cc.color(0, 0, 0).fromHEX(dataDict.strokeColor);
        path.lineWidth = dataDict.lineWidth;
        path.fillColor = 'none';

        // 映射還原點
        var pathPoints = dataDict.points;
        var userPoints = [];
        for (var i = 0; i < pathPoints.length; i++) {

            let pointDict = pathPoints[i];
            var point = cc.p(pointDict.x * this.node.width, pointDict.y * this.node.height);
            userPoints.push(point);
        }

        // 畫線並隱藏
        path.points(userPoints.reverse())
        var pathLength = path.getTotalLength();
        path.dashOffset = pathLength;
        path.dashArray = [pathLength];

        // 設置path字典
        var pathDict = {};
        pathDict.path = path;
        pathDict.duration = (dataDict.endTime - dataDict.startTime) / 1000.0;

        // 將path字典存入數組 
        this.pathArray.push(pathDict);
    },複製代碼

須要注意的事項:

① 清屏數據結構與畫線不一樣因此特殊處理。

② 線的動畫顯示,實質上是已經畫了,不過被隱藏了,只不過是在必定時間裏按比例顯示出來。

三、處理畫線隊列(在update

update: function (dt) {

        // 時間遞增
        this.time += dt;

        // 設置顯示比例
        let percent = this.time / this.duration;

        // 顯示比例超過1 更新到隊列中的下一條線
        if (percent > 1) {

            // 假如隊列有path,排除沒畫線時出錯
            if (this.pathArray.length > 0) {

                // 假如是清屏命令 直接清屏退出這次update
                if (this.pathArray[0].dataEvent === 'clear') {

                    this.clearAll();
                    this.pathArray.shift();
                    return;
                }

                // 比較是不是當前path,是的話移除
                if (this.path === this.pathArray[0].path) {

                    this.pathArray.shift();
                }
            }

            // 在移除以後(或者第一次) 判斷隊列還有沒有path,有的話繼續畫
            if (this.pathArray.length > 0) {

                // 假如是清屏命令 直接清屏退出這次update
                if (this.pathArray[0].dataEvent === 'clear') {

                    this.clearAll();
                    this.pathArray.shift();
                    return;
                }

                // 開始新一條線的顯示(初始化)
                this.path = this.pathArray[0].path;
                this.pathLength = this.path.getTotalLength();
                this.time = 0;
                this.duration = this.pathArray[0].duration;
                percent = 0;
            }
            return;
        }

        // 根據時間刷新畫筆的顯示
        this.path.dashOffset = this.pathLength * (1 - percent);
        this.path._dirty = true;
    },
});複製代碼

4、相關資源

一、raphael_github

二、raphael_demo

須要注意的事項:

① 按照raphael_demo中的安裝教程安裝時,記得後兩步即:git submodule update --initnpm install須要在終端cd到項目所在的文件夾執行,不是全局的。

5、嘿嘿!你懂得!

本文首發於個人我的博客,但願你們多多支持!

相關文章
相關標籤/搜索