画布中的多个实例:javascript

时间:2010-09-11 10:33:19

标签: html5 canvas

我这样用它..

  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();

我创建了两个canvas实例,但redLine.lineWidth over写了grayLine.lineWidth值...为什么会发生这种情况?

1 个答案:

答案 0 :(得分: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';
...