我的问题是 context.beginPath() context.closePath()。下面的代码将在屏幕周围画一个圆弧,直到消失为止,然后是一个小点,我将其注释掉,因为这是一个.jpg,我不知道如何添加。

我的问题是beginPath()以及closePath()到底是做什么的?

如果我将其注释掉,我得到的结果将超出预期。我在互联网上看过,但没有看到这样的结果。

有问题的代码:

function drawTheBall() {
    context.fillStyle = "#00AB0F"; //sets the color of the ball
    context.beginPath();
        context.arc(ball.x,ball.y,10,0,Math.PI*2,true); //draws the ball
    context.closePath();
    context.fill();
}

下面的工作代码

HTML-Javascript
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX10: Moving In Simple Geometric Spiral </title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
    canvasApp();
}

function canvasSupport () {
    return Modernizr.canvas;
}

function canvasApp() {
    var radiusInc = 2;
    var circle = {centerX:250, centerY:250, radius:2, angle:0, radiusInc:2}
    var ball = {x:0, y:0,speed:.1};
    var points = new Array();

    theCanvas = document.getElementById('canvasOne');
    context = theCanvas.getContext('2d');

    var pointImage = new Image();
    pointImage.src = "point.png";   <-- Comment this line out

    if (!canvasSupport()) {
        return;
    }

  function erraseCanvas() {
     context.clearRect(0,0,theCanvas.width,theCanvas.height);
  }

  function drawPathPoints() {
    //Draw points to illustrate path
    points.push({x:ball.x,y:ball.y});
    for (var i= 0; i< points.length; i++) {
        context.drawImage(pointImage, points[i].x, points[i].y,1,1);
    }
  }

  function drawTheBall() {
    context.fillStyle = "#00AB0F"; //sets the color of the ball
    context.beginPath();
        context.arc(ball.x,ball.y,10,0,Math.PI*2,true); //draws the ball
    context.closePath();
    context.fill();
  }

  function buildBall() {
    ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
    ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;
    circle.angle += ball.speed;
    circle.radius += radiusInc;
  }

  function  drawScreen () {
    erraseCanvas();
    buildBall();
    drawPathPoints();
    drawTheBall();
  }

    function gameLoop() {
        window.setTimeout(gameLoop, 20);
        drawScreen()
    }

    gameLoop();
}


</script>

</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">

<canvas id="canvasOne" width="500" height="500">
 Your browser does not support the HTML 5 Canvas.
</canvas>
</div>

</body>
</html>

最佳答案

beginPath()beginPath()清除当前内部路径对象及其子路径,这些对象将累积路径操作,如直线,矩形,弧线,arcTo等,无论它们是被填充还是被描边。closePath()closePath()将当前路径或子路径的位置与该路径上的第一个点(使用beginPath()moveTo()创建)连接起来。后者在当前主路径和only this sub-path gets closed上创建一个子路径。
某些方法为您执行了隐式和临时的closePath()(例如fill()clip()),这意味着这些调用不需要它。无论如何,必须在调用stroke()(或fill(),如果您选择使用它)之前调用它。
如果有人认为它是“闭合循环”而不是结束或闭合它没有的路径[对象],那么也许可以更好地理解这种方法。

08-19 14:08