HTML5 Canvas笔划宽度不会逐渐变化

时间:2016-12-11 12:45:28

标签: javascript html5 canvas

我试图逐步改变我的线宽。 但是下面的代码不起作用:

var csMargin = 10; //Color select margin
var csSize   = 15;
var csNumber = 4;

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = (csMargin * 2 + csSize) * csNumber;
canvas.height = (csMargin * 2 + csSize) * csNumber;
document.body.appendChild(canvas);

function DrawCS(){
    for(i = 0; i < csNumber; i++){
        for(j=0; j< csNumber ;j++){
            ctx.rect(csMargin*(i+1)+i*csSize,csMargin*(j+1)+j*csSize,csSize,csSize)

            //the line width should increase as j increases!!
            ctx.lineWidth=j*2;
            ctx.stroke();
        }
    }
}

DrawCS();

我应该得到一条线宽,每条线都变粗,但是从每个方块得到相同的厚度。

Wrong result

1 个答案:

答案 0 :(得分:2)

您在ctx.beginPath();

之前忘记了ctx.rect(...).

然后避免使用零宽度,例如:

ctx.lineWidth=(j+1)*2;

&#13;
&#13;
<canvas id="canvas"></canvas>
	
<script>
  var csMargin = 10; //Color select margin
  var csSize   = 15;
  var csNumber = 4;

  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  canvas.width = (csMargin * 2 + csSize) * csNumber;
  canvas.height = (csMargin * 2 + csSize) * csNumber;
  document.body.appendChild(canvas);

  function DrawCS(){
    ctx.stroke();
    for(i = 0; i < csNumber; i++){
      for(j=0; j< csNumber ;j++){
        ctx.beginPath();					
        ctx.rect(csMargin*(i+1)+i*csSize,csMargin*(j+1)+j*csSize,csSize,csSize);
        ctx.lineWidth=(j+1)*2;
        //the line width should increase as j increases!!					
        ctx.stroke();
      }
    }
  }

  DrawCS();
</script>
&#13;
&#13;
&#13;