【问题标题】:html5 animation: canvas clearing works but everything is redrawnhtml5 动画:画布清除工作,但一切都重绘
【发布时间】:2014-01-10 05:32:20
【问题描述】:

我想要一个圆圈在我的画布上移动。

因此,对于动画的每一帧,我都会清除画布并使用新的原点坐标绘制一个新圆。

逐步执行我的代码,我可以看到clearRect函数运行良好,但是每次重新绘制画布时,都会绘制新的圆和之前的所有圆,包括从第一个圆中心到的直线新的圆心。

文件index.html:

  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <title>my website</title>
    </head>
    <body onLoad="init();">
      <canvas class="circle" id="pinkCircle" width="400" height="400"
        style="border:1px solid pink;">
      </canvas>
      <script src="js/myjs.js"></script>
    </body>
  </html>

文件js/myjs.js:

//set variables
  var canvas;
  var context;
  var myCircle = {x:50,y:100,r:20};
  //offset
  var dx = 8;
  var dy = 5;
  function init() {
    //set canvas and its context
    canvas = document.getElementById('pinkCircle');
    context = canvas.getContext('2d');
    //repeat the drawCircle function for each frame
    setInterval(drawCircle,1000);
  }
  function drawCircle() {
    //clear the canvas
    context.clearRect(0,0,canvas.width,canvas.height);
    //redraw a circle with a different origin coordinates each time
    context.beginPath;
    context.arc(myCircle.x, myCircle.y, myCircle.r, 0, 2 * Math.PI, true);
    context.closePath();
    context.stroke();
    if( myCircle.x<0 || myCircle.x>400) dx=-dx; 
    if( myCircle.y<0 || myCircle.y>400) dy=-dy;
    myCircle.x+=dx;
    myCircle.y+=dy;
  }

我浏览了很多在线资源,但我不知道哪里出了问题。

【问题讨论】:

    标签: javascript html animation canvas


    【解决方案1】:

    您是否检查过页面的 Autoredraw 属性?我认为在您的情况下它必须设置为 false。

    【讨论】:

      【解决方案2】:

      您的代码几乎是正确的。但是你犯了一个小错误: 没有在下面的行中给出圆括号:

      context.beginPath;
      

      应该是:

      context.beginPath();
      

      工作JS Bin Link

      【讨论】:

      • 添加括号解决了我的问题。
      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2015-06-24
      • 1970-01-01
      相关资源
      最近更新 更多