HTML5 canvas动画和旋转

萨希尔·拉伊

我正在尝试创建一个新的画布动画,该动画包含围绕一个中心点(类似于太阳系)旋转的五个圆圈。因此,我创建了五个圆圈并尝试旋转画布:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
		<script type="text/javascript">


	var num=5, balls = [] ;

	function Ball() {
		this.r = 20;
		this.x =Math.random()*200;
		this.y = Math.random()*150;
		
	}
	
	function init() {
		
	canvas = document.getElementById("testCanvas");
		context = canvas.getContext("2d");
			
		context.clearRect(0,0,context.width,context.height);	
		context.fillStyle= "lightblue";
		
		context.save();
		context.translate(300,300);
		for(i=0; i<num ;i++){ balls[i] = new Ball() }
		setInterval(draw,50);
			
 }
		//function blank() {
				//context.fillStyle="white";
				//context.fillRect(0,0,context.canvas.width, context.canvas.height);
		//	}
		
		function draw(){
			
			context.clearRect(0,0,canvas.width,canvas.height);
			for(i=0 ; i< num ; i++){
				var Ball = balls[i];
				context.beginPath();
				context.arc(Ball.x, Ball.y, Ball.r,0,2*Math.PI, false);
				//context.stroke();
				context.fill();
						}
			context.rotate(0.08);
			context.translate(0,0);
			context.beginPath();
			context.arc(0,0,240,0,Math.PI*2,false); 
			context.lineWidth = 8;
  			context.stroke();
			}
</script>
</head>
<body onload="init()">
		<canvas id="testCanvas" width="600" height="600">
			Canvas not supported
		</canvas>
</body>
</html>

问题是该clearRect呼叫似乎无效。有时我可以从一个或多个圈子中看到“足迹”:

在此处输入图片说明

在此处输入图片说明

用户名

这里有几个问题:

  • 主要原因:在翻译画布时使用clearRect。这意味着它将无法清除整个画布。始终清除未转换
  • 一个save()永远不会恢复()-它可能打算在以后进行翻译
  • 使用requestAnimationFrame进行动画处理-效率更高。而是更改转速。
  • 如果颜色相同,也可以将所有弧添加到路径并填充。这样可以加快绘图速度。

我在下面做了一些更改-

var num = 5,
  rotation = 0,
  balls = [];

function Ball() {
  this.r = 20;
  this.x = Math.random() * 200;
  this.y = Math.random() * 150;

}

(function init() {

  canvas = document.getElementById("testCanvas");
  context = canvas.getContext("2d");

  context.clearRect(0, 0, context.width, context.height);
  context.fillStyle = "lightblue";

  for (i = 0; i < num; i++) {
    balls[i] = new Ball()
  }
  requestAnimationFrame(draw);

})();

function draw() {

  // reset transforms before clearing
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.clearRect(0, 0, canvas.width, canvas.height);

  // tramslate and rotate an absolute rotation value
  context.translate(300, 300);
  context.rotate(rotation);

  // draw arcs
  for (i = 0; i < num; i++) {
    var Ball = balls[i];
    context.beginPath();
    context.arc(Ball.x, Ball.y, Ball.r, 0, 2 * Math.PI, false);
    //context.stroke();
    context.fill();
  }
  context.beginPath();
  context.arc(0, 0, 240, 0, Math.PI * 2, false);
  context.lineWidth = 8;
  context.stroke();

  // update rotation value and request new frame
  rotation += 0.04;
  requestAnimationFrame(draw)
}
<canvas id="testCanvas" width="600" height="600">
  Canvas not supported
</canvas>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章