请问怎么去掉重复的划线?

来源:3-4 编程练习

Marcuse

2019-08-24 10:47:18

<!DOCTYPE html>

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    <style>

        body {

            background: lightpink;

        }

        * {

            margin: 0;

            padding: 0;

        }

        .mycanvas {

            border: 0px solid black;

            position: absolute;

            top: 60px;

        }

    </style>

</head>

<body>

     <canvas id="mycanvas" class="mycanvas"></canvas>

</body>

<script>

     var cans = document.getElementById('mycanvas');

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

     cans.width = 240;

     cans.height = 240;

     function drawline(times) {

        var x = 0, y = 0;

         for (var i = 0; i < times; i++) {

            ctx.moveTo(x,y);

            x += 60;

            ctx.lineTo(x , y);

            ctx.stroke(); 

            // ctx.beginPath();

            y += 60;

            ctx.lineTo(x , y );

            ctx.stroke();

            // ctx.beginPath();  

         }   

     }

     drawline(4)

     ctx.moveTo(0,240);

     ctx.lineTo(240, 240);

     ctx.stroke(); 

     

</script>

</html>


写回答

1回答

好帮手慕言

2019-08-24

同学你好,在执行moveTo、lineTo时在内存中绘制了一条路径,再执行stroke时才把线画出来。

如果在下方又执行了上面的步骤,第一条线会被绘制两次。建议:当所有路径都存在时,再绘制。

另外从0,0点开始绘制,线的粗细会有些问题,建议:不从0,0开始绘制

代码参考:

http://img.mukewang.com/climg/5d6113c900014e9a07330825.jpg

祝学习愉快~

0

0 学习 · 6815 问题

查看课程