00 Votes

HTML5 Canvas: Cannot change line width

Question by PC Control | 2014-05-22 at 23:16

I would like to draw a line onto an HTML 5 canvas varying the width of the line. For this purpose, I have developed the following code:

ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo(0, 0);        
ctx.lineTo(10, 10);

ctx.lineWidth = 2;
ctx.lineTo(20, 20);

ctx.lineWidth = 3;
ctx.lineTo(30, 30);

ctx.lineWidth = 4;
ctx.lineTo(40, 40);

...

ctx.stroke();  

Unfortunately, the line does not assume the specified line with. Instead, only the last specified width is taken and the whole line is drawn using this width. Can someone help me?

ReplyPositiveNegative
0Best Answer0 Votes

The drawing of the line happens not before calling stroke() and the line width that is set at this moment will be used for it. Every time, you have set the lineWidth without calling stroke() before, the width specified before was overwritten without drawing.

You have to proceed in a way something like this:

ctx.beginPath();
ctx.moveTo(0, 0);        
ctx.lineTo(10, 10);
ctx.lineWidth = 1;
ctx.stroke();  

ctx.beginPath();
ctx.moveTo(10, 10);        
ctx.lineTo(20, 20);
ctx.lineWidth = 2;
ctx.stroke();  


ctx.beginPath();
ctx.moveTo(20, 20);        
ctx.lineTo(30, 30);
ctx.lineWidth = 3;
ctx.stroke(); 

However, you should better use a loop instead of coding each change by hand.
2014-05-22 at 23:18

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.