首页 > 解决方案 > 为什么我不能在画布内移动我的圆圈?

问题描述

我正在尝试分别移动两个圆圈,但是尽管在 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>

标签: javascripthtmlcanvas

解决方案


推荐阅读