Creator 一笔画效果解析
看文章前请先熟读graphics组件,
废话不逼逼,直接上灵魂画家的demo效果
画笔效果 这里主要是应用graphics组件,
上代码:
cc.Class({
extends: cc.Component,
properties: {
pink: cc.Node, //色块1
yellow: cc.Node, //色块2
purple: cc.Node, //色块3
areaNode: cc.Node, //mask父节点
},
onLoad: function () {
//获取画笔组件
this.ctx = this.getComponent(cc.Graphics);
},
start() {
//触屏
this.areaNode.on(cc.Node.EventType.TOUCH_START, (touch) => {
this.onTouchBegan(touch);
}, this);
//移动
this.areaNode.on(cc.Node.EventType.TOUCH_MOVE, (touch) => {
this.onTouchMoved(touch);
}, this);
//在区域内移动结束
this.areaNode.on(cc.Node.EventType.TOUCH_END, () => {
this.onTouchEnded();
}, this);
//在区域外移动结束
this.areaNode.on(cc.Node.EventType.TOUCH_CANCEL, () => {
//清理笔刷
this.ctx.clear();
}, this);
},
//点击逻辑
onTouchBegan(touch) {
var touchLoc = touch.getLocation();
touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);
this.points = [touchLoc];
return true;
},
//移动逻辑
onTouchMoved(touch) {
var touchLoc = touch.getLocation();
touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);
this.points.push(touchLoc);
this.ctx.clear(); //清理屏幕
for (let i = 0, l = this.points.length; i < l; i++) {
let p = this.points[i];
if (i === 0) {
this.ctx.moveTo(p.x, p.y);
} else {
this.ctx.lineTo(p.x, p.y);
}
}
this.ctx.stroke();
// console.log(‘move’);
},
// 手势抬起逻辑
onTouchEnded() {
// this.ctx.clear(); //手势抬起清理画布
},
update: function (dt) {
this.pink.on(‘touchstart’, () => {
//点击色块切换画笔笔触颜色
let color = this.pink.children[0].getComponent(cc.Label).string;
this.ctx.strokeColor.fromHEX(color)
})
this.yellow.on(‘touchstart’, () => {
//点击色块切换画笔笔触颜色
let color = this.yellow.children[0].getComponent(cc.Label).string;
this.ctx.strokeColor.fromHEX(color)
})
this.purple.on(‘touchstart’, () => {
//点击色块切换画笔笔触颜色
let color = this.purple.children[0].getComponent(cc.Label).string;
this.ctx.strokeColor.fromHEX(color)
})
},
});
欢迎mark,进行补充内容