首页 > 解决方案 > javascript 我的弧没有出现或在屏幕上移动

问题描述

你好,我正在尝试在 javascript 中让一个白色圆圈穿过一个黑框我的圆圈没有显示大黑框但圆圈没有显示我不知道为什么我要在谷歌浏览器中加载页面这是代码

<html>
<head>

 <title>paddle</title>
 </head>
 <body>
  <canvas id="myCanvas" width="800" height="600"></canvas>
  <script>
  var canvas
  var canvasContext
  var ballX = 5
  window.onload = function() {

  var fps = 30;
  setInterval(updateAll, 1000)
  canvas = document.getElementById("myCanvas");
  canvasContext = canvas.getContext("2d")
 canvasContext.fillStyle = "black"
 canvasContext.fillRect(0, 0, canvas.width, canvas.height)
 }
 function updateAll() {

 ballX++

 canvasContext.fillStyle = "white";
 canvasContext.beginPath()
 canvasContext.arc(ballX, 100, 10, 0, Math.PI*2, true);
 canvasContext.stroke()
 }


 </script>
 </body>
 </html>

标签: javascriptcanvashtml5-canvas

解决方案


问题是您正在使用笔画来绘制圆圈,但您没有设置默认为黑色的笔画样式。所以你在黑色背景上画了一个黑色圆圈。因此没有看到圈子。

此外,最好使用requestAnimationFrame动画而不是设置间隔。

动画圆的示例

requestAnimationFrame(animationLoop);
const ctx = myCanvas.getContext("2d");
var ballX = 5;
var speed = 1
const radius = 10;
const fps = 30;
var frameCount = 0;

function animationLoop() {
    if (frameCount % (60 / fps) === 0) {
        ctx.fillStyle = "black"
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        draw();
    }
    frameCount ++;
    requestAnimationFrame(animationLoop);

}
function draw() {
    ballX = (ballX + speed) % (ctx.canvas.width + radius * 2);
    ctx.strokeStyle = "white";
    ctx.lineWidth = 2;
    ctx.beginPath()
    ctx.arc(ballX - radius, 20, 10, 0, Math.PI * 2);
    ctx.stroke()
}
<canvas id="myCanvas" width="600" height="40"></canvas>


推荐阅读