felixo
felixo

Reputation: 1613

How to style closePath() in canvas?

I am trying to style the closePath() on my canvas but am at a loss on how to do that, as a matter of fact I would actually like all the lines to have a different style, for this question lets stick to getting different colors. ! As you can see I have a triangle, how can I have differing strokestyles for each line? Here is link to the Code Pen

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(20, 140); 
ctx.lineTo(120, 10);  
ctx.strokeStyle = "green";
ctx.lineTo(220, 140); 
ctx.closePath();  
ctx.strokeStyle = "blue";
ctx.stroke();
<canvas id="canvas"></canvas>

Upvotes: 1

Views: 211

Answers (2)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You would need to have the three lines as three separate paths.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(20, 140); 
ctx.lineTo(120, 10); 
ctx.strokeStyle = "red";
ctx.stroke();

ctx.beginPath();
ctx.moveTo(120, 10); 
ctx.lineTo(220, 140); 
ctx.strokeStyle = "green";
ctx.stroke();

ctx.beginPath();
ctx.moveTo(220, 140); 
ctx.lineTo(20, 140); 
ctx.strokeStyle = "blue";
ctx.stroke();
<canvas id="canvas"></canvas>

Upvotes: 3

enhzflep
enhzflep

Reputation: 13099

Each segment needs to be coloured.

function qsa(sel,par=document){return par.querySelectorAll(sel)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
	draw();
}

class vec2d
{
	constructor(x=0,y=0)
	{
		this.x = x;
		this.y = y;
	}
}

function draw()
{
	var verts = [ new vec2d(20,140), new vec2d(120, 10), new vec2d(220,140) ];
	var colours = ['red', 'green', 'blue'];

	let can = qsa('canvas')[0];
	let ctx = can.getContext('2d');
	
	var numLineSegs = verts.length;
	for (var lineSegIndex=0; lineSegIndex<numLineSegs; lineSegIndex++)
	{
		var index1 = lineSegIndex;
		var index2 = (lineSegIndex+1)%verts.length;
		
		ctx.beginPath();
		ctx.strokeStyle = colours[index1];
		ctx.moveTo(verts[index1].x, verts[index1].y);
		ctx.lineTo(verts[index2].x, verts[index2].y);
		ctx.stroke();
	}
	ctx.closePath();
}
<canvas width=512 height=512></canvas>

Upvotes: 2

Related Questions