html canvas 线宽工作不正常

html canvas linewidth not working properly

我在 canvas 中使用 javascript 画了几条线,我正在更改 3 条不同线(两个轴,底部 10 条线和顶部 10 条线)的线宽值。当我更改前两行的 lineWidth 属性 时(lineWidth = 2.5 和 lineWidth = 1.0),它工作正常。但是,当我添加最后一个 lineWidth 属性 = 2.0 时,它不起作用并且会发生变化。我已经把代码放在这个 fiddle 里了。任何帮助将不胜感激。

http://jsfiddle.net/pwp2ps09/1/

<canvas id="graph" width="550" height="400"></canvas>

$(document).ready(function(){
var p= 50;
graph = $('#graph');
var g = graph[0].getContext('2d');

drawlines();

function drawlines(){
    g.beginPath();
    //brings cursor to the origin of this line graph
    g.moveTo(p, graph.height() - p);
    //creates x-axis
    g.lineTo(graph.width() - p, graph.height() - p);
    g.moveTo(p, graph.height() - p);
    //creates y-axis
    g.lineTo(p, p);
    g.lineWidth = 2.5;
    g.font = '12px Arial';
    g.stroke();

    g.lineWidth = 1.0;

    for (i=10; i<101; i+=10){
        g.moveTo(p, graph.height() - p - i);
        //creates x-axis
        g.lineTo(graph.width() - p, graph.height() - p - i);
    }
    g.stroke();

    g.lineWidth = 2.0;

    for (i=110; i<201; i+=10){
        g.moveTo(p, graph.height() - p - i);
        //creates x-axis
        g.lineTo(graph.width() - p, graph.height() - p - i);
    }
    g.stroke();
}
});

记得在添加新行之前使用 beginPath()。该路径将使用最新设置的线宽呈现。 beginPath() 将清除之前的路径和添加的行。

如果您不清除路径,新的 stroke() 调用将在旧行之上添加新添加的行。随着线宽变粗,新线将简单地透支旧线。

更新代码(来自fiddle):

$(document).ready(function() {
  var p = 50;
  graph = $('#graph');
  var g = graph[0].getContext('2d');

  drawlines();

  function drawlines() {
    g.beginPath();
    //brings cursor to the origin of this line graph
    g.moveTo(p, graph.height() - p);
    //creates x-axis
    g.lineTo(graph.width() - p, graph.height() - p);
    g.moveTo(p, graph.height() - p);
    //creates y-axis
    g.lineTo(p, p);
    g.lineWidth = 2.5;
    g.font = '12px Arial';
    g.stroke();

    g.beginPath();  // <--- Define new path here

    g.lineWidth = 1.0;

    for (i = 10; i < 101; i += 10) {
      g.moveTo(p, graph.height() - p - i);
      //creates x-axis
      g.lineTo(graph.width() - p, graph.height() - p - i);
    }
    g.stroke();

    g.beginPath();  // <--- and here, etc.

    g.lineWidth = 2.0;

    for (i = 110; i < 201; i += 10) {
      g.moveTo(p, graph.height() - p - i);
      //creates x-axis
      g.lineTo(graph.width() - p, graph.height() - p - i);
    }
    g.stroke();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="graph" width="550" height="400"></canvas>