canvas小球拋物線運動

admin發表於2018-03-15

分享一段程式碼例項,它利用canvas實現了小球的拋射效果。

簡單的拋物線效果,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
html,body,canvas{
  width:100vw;
  height:100vh;
  background:#000000;
  overflow:hidden;
}
</style>
<script>
setTimeout(() => {
  let canvas = document.querySelector('canvas');
  let context = canvas.getContext('2d');
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;

  let pointer = {
      x: 0,
      y: canvas.height / 2
  };

  let render =  () => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "green";
    context.beginPath();
    context.arc(pointer.x ,pointer.y, 100, 0, 2 * Math.PI, false);
    context.fill();
  };

  let vx = 7;
  let vy = -7;
  let run;
  ( run= () => {
    pointer.x += vx; // 位置恆定變化
    vy += 0.1; // 速度恆定變化
    pointer.y += vy;

    if (pointer.x > canvas.width 
       || pointer.y > canvas.height) {
      pointer.x = 0;
      pointer.y = canvas.height / 2;
      vy = -7;
    }
    render();
    requestAnimationFrame(run)
  })();
}, 500);
</script>
</head>
<body>
<canvas></canvas>
</body>
</html>


相關文章