CocosCreator之KUOKUO带你用cc.graphics做个小画板

本次引擎2.0.5

编辑工具VSCode

如遇不会某个步骤可以先过一遍之前教程,或者下方评论,感谢支持!

目标:使用cc.graphics组件完成一个小画板

啦啦啦,让我们快乐地画画去!

好了,新建工程,建个白色背景,再加个空节点起名为draw

给draw添加渲染组件-->cc.graphics组件。

调整属性:(代码里也可以修改)

好了,让我们新建个JavaScript脚本,起名字为draw,绑定给Canvas。

打开脚本,删去注释,声明个cc.graphics;

保存脚本(保存场景)

然后,把draw节点拖过去:

 这样,我们先简单写个线条。

    onLoad () {
        // 设置线条宽度
        this.draw.lineWidth = 5;
        // 路径起点为0,0
        this.draw.moveTo(0,0);
        // 路径画线到(100,100)
        // 路径看不见!!!
        this.draw.lineTo(100,100);
        // 把路径画实,能看见啦!
        this.draw.stroke();
    },

注意,是先moveTo给个画笔起点,然后画路径。

最后用stroke()方法把路径描绘。

看看效果:

好了,完成了,我们接下来做一下手指触摸绘画。给出代码。

cc.Class({
    extends: cc.Component,

    properties: {
        draw : cc.Graphics,
    },

    onLoad () {
        // 设置线条宽度
        this.draw.lineWidth = 5;
    },

    start () {
        // 手指触摸开始,移动起点到触摸点
        this.node.on('touchstart',function(touch) {
            var t_pos = touch.getLocation();
            var pos = this.node.convertToNodeSpaceAR(t_pos);
            this.draw.moveTo(pos.x,pos.y);
        },this);
        // 手指移动,不断绘图
        this.node.on('touchmove',function(touch) {
            var t_pos = touch.getLocation();
            var pos = this.node.convertToNodeSpaceAR(t_pos);
            this.draw.lineTo(pos.x,pos.y);
            this.draw.stroke();
        },this);
    },
});

(其实把脚本直接绑定在draw这个空节点上也是可以的,但是要注意把节点大小改一下。)

让我画个画:

真丑!

好了,基础的绘画有了,让我们加几个功能:

先弄几个按钮上去:

然后我们写一下脚本中的方法:

我相信不给注释你也能看懂!

然后我们拖,拖,拖,,,,,,

好累,不过看到成功后的画板还是很开心呢!O(∩_∩)O~~!! 

怎么样,学到了吗?

想知道怎样在Cocos没给撤销一步方法的情况下撤销一步吗?

我会在日常小制作(中级)中给出。

O(∩_∩)O~~

猜你喜欢

转载自blog.csdn.net/kuokuo666/article/details/84778212