javascript - 为什么我不能在画布内移动我的圆圈?
问题描述
我正在尝试分别移动两个圆圈,但是尽管在 w3school 或 youtube 上进行搜索,我似乎无法让这两个圆圈移动,我知道如何移动一个圆圈但是当我尝试通过创建构造函数来移动两个圆圈时它失败了.
我敢肯定这是一个愚蠢的问题,但我不禁要问。
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
let ball = new drawCircle(50, 50, 20);
let ballTwo = new drawCircle(100, 100, 20);
function drawCircle(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.draw = function() {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI *2);
ctx.fillStyle = "lightskyblue";
ctx.fill();
}
}
function draw() {
ball.x += 1;
ball.draw();
ballTwo.x += 1;
ballTwo.draw();
if (x + r > canvas.width || x < r) {
dx = -dx;
}
if (y + r > canvas.width || y < r) {
dy = -dy;
}
requestAnimationFrame(draw)
}
draw();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Círculo</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
}
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
</body>
<script src="/js/canvasTwo.js"></script>
</html>
解决方案
推荐阅读
- bazel - 如何使 sh_test 依赖于构建 docker 镜像?
- python - 如何计算累积平均收入?Python
- angular - 如何在 Angular 9/TypeScript 中添加垂直滚动条
- firebase - firebase 多区域的优势
- python - 保存的模型无法加载包含自定义方法的层
- javascript - .getValues 无法读取自定义函数
- logstash - ElasticStack 中的架构 logstash 配置文件
- excel - VBA 数字格式货币 2dp
- python - 使用 pandas 读取 csv 文件时使用哪种编码?
- amazon-web-services - 如何在 Amazon Cognito 和其他微服务之间建立关系?