javascript - 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>
解决方案
问题是您正在使用笔画来绘制圆圈,但您没有设置默认为黑色的笔画样式。所以你在黑色背景上画了一个黑色圆圈。因此没有看到圈子。
此外,最好使用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>
推荐阅读
- node.js - sql.close() 如果 object = sql.connect 并且 object 最后被销毁,是否仍然需要?(Node.js 快递)
- javascript - 使用具有 PHP 功能的表单提交后禁用按钮。没有 jQuery
- wordpress - WordPress 菜单:从 ul 中删除第三级的类
- objective-c - 如何集成 Sagepay iOS SDK
- python - 如何减少 Python Firebase Admin SDK 中的 SSL 开销
- python - 如何在 Python 中水平而不是垂直地执行此操作?
- java - 出于调试目的,如何在 Java Google App Engine 应用程序中打印和查看字符串?
- algorithm - 树捕获问题将另一个玩家放置在哪里以获得最高分
- pyside2 - PySide2 项目的 fbs 项目结构
- r - R代码使用最后一列对齐所有行的长度