Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly draw many different-width lines on the HTML5 canvas?

I'm working on a program that should draw a mindmap-like network of objects on the screen, and then draw the connections between the objects. The width of the line should represent the strength of the connection. The connections are altered over time, but many connections are drawn incorrectly. I am 100% sure that I actually alter the correct connection, and that I just draw it badly.

So, here's how I try to draw it, can you please tell me what am I doing wrong? And how do I do it right?

  for (o = 0; o < self.brain.objects.length; o++)
       for (con =  0; con < self.brain.objects[o].connections.length; con++)
       {
            self.screen.lineWidth = Math.sqrt(self.brain.objects[o].connections[con].weight)*5*self.zoom;

            self.screen.beginPath();
            self.screen.moveTo((self.brain.objects[o].rect[0] - self.globalPos[0])*self.zoom + (self.brain.objects[o].rect[2]/2)*self.zoom, (self.brain.objects[o].rect[1] - self.globalPos[1] + self.brain.objects[o].rect[3]/2)*self.zoom);
            self.screen.lineTo((self.brain.objects[o].connections[con].to.rect[0] - self.globalPos[0] + self.brain.objects[o].connections[con].to.rect[2]/2)*self.zoom, (self.brain.objects[o].connections[con].to.rect[1] - self.globalPos[1] + self.brain.objects[o].connections[con].to.rect[3]/2)*self.zoom);
            self.screen.stroke();
       }
like image 373
corazza Avatar asked Nov 26 '11 18:11

corazza


1 Answers

You have the correct code to draw different-width Lines.

Here is a jsFiddle that shows the code in action, http://jsfiddle.net/q9LRs/

The problem is likely cause when you calculate your lineWidth. You may also need to call closePath() in some browsers.

Try simplifying your example and post working code so we can see where the problem lies.

like image 132
Charles Avatar answered Nov 01 '22 09:11

Charles