Graphics free hand drawing with a touch movement is producing a weird bug

Hello,
This is what I need and it does work this way most of the time.
Screenshot 2023-04-11 at 12.29.49 PM
But somethimes I get this while drawing
Screenshot 2023-04-11 at 12.28.39 PM
Not sure why.
This is the code.

let graphics, graphicNode: cc.Node;
this.node.on(cc.Node.EventType.TOUCH_START, (event) => {
    graphicNode = new cc.Node();
    this.graphicsDraw.addChild(graphicNode);
    graphics = graphicNode.addComponent(cc.Graphics);
    let g = graphics;
    var nodePositionWrtWorld = this.node.parent.convertToWorldSpaceAR(event.getLocation());
    var canvasNode = cc.find('Canvas');
    this.lastPos = canvasNode.convertToNodeSpaceAR(nodePositionWrtWorld);
    g.lineWidth = 5;
    g.moveTo(this.lastPos.x, this.lastPos.y);
})

this.node.on(cc.Node.EventType.TOUCH_MOVE, (event: cc.Touch) => {
    let g = graphics;
    var nodePositionWrtWorld = this.node.parent.convertToWorldSpaceAR(event.getLocation());
    var canvasNode = cc.find('Canvas');
    g.lineTo(canvasNode.convertToNodeSpaceAR(nodePositionWrtWorld).x, canvasNode.convertToNodeSpaceAR(nodePositionWrtWorld).y);
    g.stroke();

    this.lastPos = canvasNode.convertToNodeSpaceAR(nodePositionWrtWorld);
});

this.node.on(cc.Node.EventType.TOUCH_END, (event: cc.Touch) => {
    let g = graphics;
    g.close()
    g.stroke();
    g.fillColor = new cc.Color(255, 0, 0, 255);
    g.fill();
});

Can someone guide me?

That could be problematic when you have multiple touch point on screen, because you share the same graphics and graphicNode variable.

The effect you are seeing looks most likely every move step closed the path, but I really can’t be sure what’s happening.

My suggestion is to reuse the same graphics component and graphics node, wrap them in a prefab, just clear path when touch start, and close path when touch ends.
If you need more paths, for example for multi touch, you need to have multiple sets of graphics prefab.

If you do that, you can also easily debug whether your path gets cleared during move

Each time after stroke(), execute moveTo() again

1 Like