Drawing a simple line in JS

I’m trying to draw a simple line. I found this code below:

var line = new cc.DrawNode();
line.drawSegment(cc.p(x,y), cc.p(x-60,y),2);

Though it doesn’t seem to work. What is the proper way of drawing a line segment?

Thanks!

I draw it like this:

this.drawing = this.node.getComponent(cc.Graphics);    
this.drawing.lineWidth = 6;
this.drawing.moveTo(x, y);
this.drawing.lineTo(x2, y2);
this.drawing.strokeColor = cc.Color.RED;
this.drawing.stroke();

Thanks for the answer.

In case anyone is looking for drawNode … here’s how I got (from this forum thread)

 onLoad: function () {
       var drawNode = new cc.DrawNode();
        drawNode.drawSegment(cc.p(0,0), cc.p(200,300),2,cc.Color(250,0,0,255));
        this.node._sgNode.addChild(drawNode);
    },

script is added to an empty node. But using graphics is better I think…

1 Like

Still doesn’t work for me. Says "this.drawing is null’.

Sorry, I’m new to cocos2d.

It may be the way I’m using it. I’m not drawing something on the ‘onLoad’ function, but rather drawing several lines based on the current X,Y of the player. Essentially, I have the player which gets a path and then I want to use a ‘drawPaths’ function to draw the line segments of the path he/she will take. (I already know the path…the x and y’s of each step/part)

maybe a better way to ask is: “how do I draw segments based on the current node’s x and y, dynamically”?

You have to add a Graphics component, in the node you are going to draw.
The code above assumes you are drawing in you own node.

You could also add a child node, called ‘drawing’ for example, and add the Graphics component in there

then…

this.drawing = this.node.getChildByName('drawing').getComponent(cc.Graphics);
this.drawing.lineWidth = 6;
this.drawing.moveTo(x, y);
this.drawing.lineTo(x2, y2);
this.drawing.strokeColor = cc.Color.RED;
this.drawing.stroke();

thanks! that worked.

It sure is, cc.Graphics also uses DrawNode inside of it, but it also covers a lot of life-cycle issues like resizing node and proper destruction. Doing as you suggest you’ll probably have memory leaks

Thanks everyone, I was able to get it working using the drawNode. Odd thing is the color is white instead of my cc.Color(255,0,0,255) which I thought would be red. That seems like something I’ll be able to figure out, but if you have an idea let me know.