cocos creator 版本使用 至少适配版本2.3.2以上
案例:
简要思路:MOUSE_MOVE事件和Graphics组件实现
前端也可以通过canvas和mousemove事件实现,原理一致
具体步骤如下:
1.添加节点Node
2.在Node节点上绑定组件Graphics
3.添加下方脚本drawcontroll.ts
4.注意Node节点的锚点和位置(如果不想要这个方法,可以看最下方解决方案)
drawcontroll.ts
全部代码
import { _decorator, Component, Color, Node, Graphics, Vec3, UITransform } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('drawcontroll')
export class drawcontroll extends Component {
graphics=null;
isDrawing = false;
array = [];
start() {
this.graphics = this.getComponent(Graphics);
this.graphics.lineWidth = 5;
this.graphics.strokeColor = Color.RED;
this.node.on(Node.EventType.MOUSE_DOWN, this.onMouseDown, this);
this.node.on(Node.EventType.MOUSE_MOVE, this.onMouseMove, this);
this.node.on(Node.EventType.MOUSE_UP, this.onMouseUp, this);
}
onMouseDown (event) {
this.isDrawing = true;
this.graphics.moveTo(event.getLocation().x,event.getLocation().y);
}
onMouseMove (event) {
if (this.isDrawing) {
this.graphics.lineTo(event.getLocation().x,event.getLocation().y);
this.graphics.stroke();
}
}
onMouseUp (event) {
this.isDrawing = false;
}
}
注意事项:
当如果发现鼠标画出来的线和鼠标轨迹有很大偏移,有两种方法
- 浏览器是否是缩小放大状态 -----调整为百分之百
- 锚点和位置设置的问题
创建的Node脚本的锚点和位置在不变的情况下(锚点0.5,0.5,位置0,0)
那么只需要将上面drawcontroll.ts
代码替换即可
onMouseDown (event) {
this.isDrawing = true;
const moveToPoint = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(event.getLocation().x,event.getLocation().y,0));
this.graphics.moveTo(moveToPoint.x,moveToPoint.y);
}
onMouseMove (event) {
if (this.isDrawing) {
const lineToPoint = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(event.getLocation().x,event.getLocation().y,0));
this.graphics.lineTo(lineToPoint.x,lineToPoint.y);
this.graphics.stroke();
}
}
convertToNodeSpaceAR方法解说如下:
关键词:
cocos creator 鼠标画笔|画线, cocos creator画线 , cocos creator 画笔, cocos creator 画形状, cocos creator 画图