【问题标题】:lineTo() Not workinglineTo() 不工作
【发布时间】:2016-10-06 05:21:51
【问题描述】:

lineTo() 函数对我不起作用,为什么?这是代码。

<canvas id="sid" height="1000px" width="1000px"> </canvas>
<script>
    var can = document.querySelector('#sid');

    var a = can.getContext('2d');

    a.beginPath();
    a.moveTo(0, 0);
    a.lineTo(140, 140);
    a.lineTo(160, 160);

</script>

【问题讨论】:

  • 您看到或没看到什么?你检查过你的画布有宽度和高度吗?最后你还需要 stroke() 。

标签: javascript html canvas


【解决方案1】:

您忘记调用stroke() 函数。查看文档对您很有帮助,其中的解释更清晰。

来自docs

Canvas 2D API 的 CanvasRenderingContext2D.stroke() 方法使用非零缠绕规则以当前笔划样式笔划当前或给定路径。

<canvas id="sid" height="1000px" width="1000px"></canvas>   
<script>
  var can = document.querySelector('#sid');

  var a = can.getContext('2d');

  a.beginPath();
  a.moveTo(0, 0);
  a.lineTo(140, 140);
  a.lineTo(160, 160);
  // After this you need to run the stroke command to get the line.
  a.stroke();
</script>

【讨论】:

    【解决方案2】:

    在定义线后,您不会抚摸它。只需添加stroke() 方法即可。

    <canvas id="sid" height="1000px" width="1000px">       </canvas>   
    <script>
    var can = document.querySelector('#sid');
    var a = can.getContext('2d');
    a.beginPath();
    a.moveTo(0, 0);
    a.lineTo(140, 140);
    a.lineTo(160, 160);
    a.stroke();  // This line is the import one being omitted.
    a.closePath(); // You should close your path also. Not absolutely necessary in this case, given that stroke() will do this for you.
    </script>
    

    【讨论】:

    • 您不需要ctx.closePath() 电话。请参阅上面我对 Praveen 回答的评论。
    • 是的,在这种情况下这不是绝对必要的,但值得向 OP 指出以供他们将来参考:)
    【解决方案3】:

    这对你有帮助:

    <html>
    <head>
       <meta charset="utf-8">
    
    </head>
    <body>
       <canvas id="sid" height="1000px" width="1000px"></canvas>   
       <script>
            var can = document.getElementById("sid");
            var a = can.getContext('2d');
            a.beginPath();
            a.lineWidth = "5";
            a.strokeStyle = "green";
            a.moveTo(0,0);
            a.lineTo(140,140);
            a.lineTo(160,160);
           a.stroke();
       </script>      
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2020-03-18
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多