javascript - 球从中心而不是边缘反弹
问题描述
我编写了一个球在画布上弹跳,但是,球只从中心弹跳,而不是从边缘弹跳。
我已经尝试使用半径而不是 x 和 y 但这根本没有帮助,因为现在我没有想法。
我希望球会从自身的边缘而不是中心反弹
<!DOCTYPE>
<html>
<head>
<title>Ball Bounce</title>
<style>
canvas {
border-width: 5px;
border-style: ridge;
border-color: #FF0000;
}
</style>
</head>
<body>
<canvas id="testCanvas" width="700" height="400"></canvas>
<script>
var canvas = document.getElementById("testCanvas");
var ctx = canvas.getContext("2d");
var x = 300;
var y = 300;
var radius = 50;
var circleColour = "green";
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var dx = 2;
var dy = -2;
function circle(x, y, r, c) {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill()
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(x, y, radius, circleColour)
if (y<0 || y > canvasHeight){
dy = -dy;
}
if (x>canvasWidth || x<0){
dx = -dx;
}
x = x + dx;
y = y + dy;
}
setInterval(draw, 5.5);
</script>
</body>
</html>
解决方案
我已经尝试过使用半径而不是 x 和 y 但这根本没有帮助......
您需要将半径与 x 和 y(或画布边缘)结合起来,以确保球在所有四个边界处改变方向。
if (y - radius < 0 || y + radius > canvasHeight) {
dy = -dy;
}
if (x + radius > canvasWidth || x - radius < 0) {
dx = -dx;
}
推荐阅读
- java - MVC:模型或控制器/视图中的坐标和形状方法?
- css - 如何在带有ruby on rails的伪元素中显示来自svg sprite的图标
- laravel - 发生错误:ArtisanLambdaFunction - 解压后的大小必须小于 220606645 字节(服务:Lambda,状态码:4000
- mongodb - 如何使用 mongodb 在环回 4 中实现 groupBy?
- react-native - 从图库中获取图像的 url 并将图像从设备转换为 tensor3d
- git - 如果不存在标签,则获取第一次提交
- java - Android Studio (Windows) 中的 Flutter 错误:无法识别的选项:--add-opens
- reactjs - 如何使用 Storybook 制作别名?
- django - 通用 DeleteView 在 0x04725628 返回 django.db.models.query_utils.DeferredAttribute 对象 - Django
- microsoft-graph-api - ms botframework 附件无法生成共享链接