0

实际上我是 html5 的新手,想用画布做一些事情,我创建的函数是从点开始绘制短射线长度并以点结束,问题是当我复制该函数以同时运行两次时不能正常工作,我的代码哪里有问题?首先我创建画布

<canvas id="mycanvas" width="1120" height="700" style="margin:auto;border:1px solid #000000;position:relative;z-index: 10;">
    </canvas>

然后我创建两次调用一个函数

var path1Number=0;
    window.addEventListener('load', function () {
    var x = 185, y = 185;
        direction1(x,y , path1Number);
        direction1(x+91,y+91 , path1Number);
    }, false);

然后我创建一个从点到点绘制路径的函数

function direction1(x,y , path1Number){
        //draw canvas line
            var canvas1 = document.getElementById('mycanvas');
            var context = canvas1.getContext('2d');
            var x2 = x;
            var y2 = y;
            var ini_x = x;
            var ini_y = y;
            var done = false;
            var interval = setInterval(function() {
            context.clearRect(0, 0, canvas1.width, canvas1.height);
            context.beginPath();
            context.moveTo(x, y);
            if(x2<x+20 && !done){
                context.lineTo(x2, y2);
                context.closePath();
                context.strokeStyle = 'red';
                context.stroke();
                x2+=1;
                y2+=1;
            }else{
                done = true;
                x+=1;
                y+=1;
                if(x2 >= ini_x + 91){
                    if(x2 == x){
                        clearInterval(interval);
                        context.closePath();
                        context.clearRect(0, 0, canvas1.width, canvas1.height);
                        path1Number+=1;
                        path1(x,y,path1Number);
                    }
                }else{
                    x2+=1;
                    y2+=1;
                }
                context.lineTo(x2, y2);
                context.closePath();
                context.strokeStyle = 'red';
                context.stroke();
            }
            },10);
    }

当我两次调用此函数时出现问题,它无法正常工作,那是什么原因?谢谢 。

4

0 回答 0