javascript - HTML5 Canvas 将圆形变为方形
问题描述
我想创建一个画布,上面有一个 100x100 像素的蓝色方块。将正方形放置在页面左侧,距顶部 50 像素。使用 javascript 为这个正方形设置动画,使其每秒向右移动 10 个像素,向下移动 10 个像素。当框碰到或越过窗口边缘时,更改相关轴的方向。
以下画布返回蓝色圆圈,但我想要 100X100px 正方形而不是圆形。我试过rect(50, 50, 50, 50);
但动画停止工作
<style type="text/css">
canvas{
border-style: inset;
background-color: lightgray;
border-radius: 5px;
}
</style>
</head>
<body style="background-color: gray;" onload="animate()">
<canvas id="bouncyBall" width="500" height="250">
</canvas>
<script type="text/javascript">
var animation;
var centerX = 50;
var centerY = 50;
var radius = 20;
var boardX = 500;
var boardY = 250;
var ballDx = 2;
var ballDy = 2;
function drawBall() {
var content = document.getElementById("bouncyBall");
var me = content.getContext("2d");
me.clearRect(0,0,content.width,content.height);
centerX = centerX + ballDx;
centerY = centerY + ballDy;
me.beginPath();
me.arc(centerX,centerY,radius,0,Math.PI*2,false);
me.stroke();
me.fillStyle = "blue";
me.fill();;
me.stroke();
if (centerY > boardY - radius || centerY - radius < 0) {
ballDy = -1*ballDy;
}
if (centerX > boardX - radius || centerX < radius) {
ballDx = -1*ballDx;
}
}
function animate() {
clearInterval(animation);
setInterval(drawBall, 25);
}
</script>
</body>
解决方案
你可以使用矩形
var animation;
var centerX = 50;
var centerY = 50;
var radius = 0;
var boardX = 500;
var boardY = 250;
var ballDx = 2;
var ballDy = 2;
var width = 100;
var height = 100;
function drawBall() {
var content = document.getElementById("bouncyBall");
var me = content.getContext("2d");
me.clearRect(0,0,content.width,content.height);
centerX = centerX + ballDx;
centerY = centerY + ballDy;
me.beginPath();
me.rect(centerX,centerY,width,height);
me.stroke();
me.fillStyle = "blue";
me.fill();;
me.stroke();
if (centerY > boardY - width || centerY - radius < 0) {
ballDy = -1*ballDy;
}
if (centerX > boardX - height || centerX < radius) {
ballDx = -1*ballDx;
}
}
function animate() {
clearInterval(animation);
setInterval(drawBall, 25);
}
animate();
canvas{
border-style: inset;
background-color: lightgray;
border-radius: 5px;
}
<canvas id="bouncyBall" width="500" height="250">
</canvas>
推荐阅读
- c - malloc():内存损坏;中止(核心转储)
- javascript - 调用函数时Jquery返回空值
- swift - Swift scheduleTimer 滞后?
- here-api - Flow API 历史数据
- python-3.x - Python sqlalchemy - 保存一对多的许多对象
- django-models - Django过滤器'in'等效
- json - 如何使用 Python 解析 SQS JSON 消息
- flutter - Flutter 中的 Material Design 主题
- ios - 如何将初始值传递给拆分视图控制器的详细信息?
- javascript - 如何使用 Next.js 为 UserContext.Provider 设置值?