2016-02-29 152 views
1

我需要使用不同顏色的線條連接的路徑,但是當我分配最後一種顏色時,整個路徑變爲單一顏色。 lines assignment在HTML5畫布中創建線條

我的代碼是

var canvas=document.getElementById("mycanvas"); 
var ctx=canvas.getContext('2d'); 

ctx.strokeStyle="#f00"; 
ctx.lineWidth=5; 
ctx.moveTo(100,100); 
ctx.lineTo(150,150); 
ctx.stroke(); 
ctx.strokeStyle="#0f0"; 
ctx.moveTo(150,150); 
ctx.lineTo(350,200); 
ctx.stroke(); 
ctx.strokeStyle="#00f"; 
ctx.moveTo(350,200); 
ctx.lineTo(400,400); 
ctx.stroke(); 

回答

2

必須調用ctx.beginPath()開始每個畫布路徑即

var canvas=document.getElementById("mycanvas"); 
var ctx=canvas.getContext('2d'); 

ctx.beginPath(); 
ctx.strokeStyle="#f00"; 
ctx.lineWidth=5; 
ctx.moveTo(100,100); 
ctx.lineTo(150,150); 
ctx.stroke(); 

ctx.beginPath(); 
ctx.strokeStyle="#0f0"; 
ctx.moveTo(150,150); 
ctx.lineTo(350,200); 
ctx.stroke(); 

ctx.beginPath(); 
ctx.strokeStyle="#00f"; 
ctx.moveTo(350,200); 
ctx.lineTo(400,400); 
ctx.stroke();