如何在画布上设置closePath()的样式?

时间:2019-05-13 09:05:47

标签: javascript html5 canvas

我试图在我的画布上设置closePath()的样式,但是如何做到这一点却不知所措,事实上,我实际上希望所有行都具有不同的样式,因为这个问题让我们坚持得到不同的颜色。 !如您所见,我有一个三角形,如何为每条线设置不同的笔触样式?这里是指向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>

2 个答案:

答案 0 :(得分:2)

您需要将三行作为三个单独的路径。

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>

答案 1 :(得分:1)

每个部分都需要着色。

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>