2010-09-11 29 views
0

我使用这种方式..多个实例:JavaScript的

var canvas = document.getElementById("canvas"); 
    var contextGrayLine= canvas.getContext("2d"); 
    var contextRedLine= canvas.getContext("2d"); 

    contextGrayLine.lineWidth = 50; 
    contextRedLine.lineWidth = 20; 
    contextGrayLine.beginPath(); 

    contextGrayLine.moveTo(10,10); 
    contextGrayLine.lineTo(500,10) 

    contextGrayLine.strokeStyle = "#AAA"; 
    contextGrayLine.stroke(); 

我创建了帆布的两个实例,但redLine.lineWidth在写grayLine.lineWidth值......为什么会这样???

回答

1

因为contextGrayLinecontextRedLine都指向相同的上下文对象。您需要独立绘制两条样式的路径,例如

var ctx = canvas.getContext('2d'); 

ctx.lineWidth = 50; 
ctx.strokeStyle = '#aaaaaa'; 
ctx.beginPath(); 
ctx.moveTo(10, 10); 
ctx.lineTo(500, 10); 
ctx.stroke(); 

ctx.lineWidth = 20; 
ctx.strokeStyle = '#ff0000'; 
... 
+0

任何良好的资源来学习帆布的细节..和任何良好的lib用于开发画布代码..就像上面的一个。 – goutham 2010-09-11 10:54:19

+0

https://developer.mozilla.org/zh/Canvas_tutorial – DevAno1 2011-05-17 12:32:58