【问题标题】:Bouncing ball in Canvas- Need it to change colorCanvas 中的弹跳球 - 需要它来改变颜色
【发布时间】:2015-10-26 03:51:30
【问题描述】:

我像大多数人一样创建了一个弹跳球游戏,我想在点击球时改变颜色。我看到很多关于如何制作我所做的东西的教程,但没有告诉我如何做我想做的事。有没有人有任何想法可以帮助我。这是我的jsfiddle

var ball;
var x = 100;
var y = 200;
var dx = 3;
var dy = 3.5;

function init() {
    ball = myCanvas.getContext('2d');
    setInterval(draw, 12);
    canvas.addEventListener('mousemove', ev_mousemove, false);
}

function draw() {
    ball.clearRect(0, 0, 600, 500);
    ball.beginPath();
    ball.fillStyle = " #F7742C";
    // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
    ball.arc(x, y, 10, 0, Math.PI * 2, true);
    ball.closePath();
    ball.fill();
    // Boundary Logic
    if (x < 10 || x > 590) dx = -dx;
    if (y < 10 || y > 490) dy = -dy;
    x += dx;
    y += dy;
}
<body onLoad="init();">
    <canvas id="myCanvas" width="600" height="500" style="border:10px solid"></canvas>
</body>

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    我分叉了你的JSFiddle,到目前为止它似乎工作但如果点在圆圈内,则测试有问题。

    <script>
        var ball;
        var x = 100;
        var y = 200;
        var dx = 3;
        var dy = 3.5;
        var color = " #F7742C";
    
        function init() {
            ball = myCanvas.getContext('2d');
            setInterval(draw, 12);
            myCanvas.addEventListener('click', ev_click, false);
        }
    
        function draw() {
            ball.clearRect(0, 0, 600, 500);
            ball.beginPath();
            ball.fillStyle = color;
            // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
            ball.arc(x, y, 10, 0, Math.PI * 2, true);
            ball.closePath();
            ball.fill();
            // Boundary Logic
            if (x < 10 || x > 590) dx = -dx;
            if (y < 10 || y > 490) dy = -dy;
            x += dx;
            y += dy;
        }
    
        function ev_click(e) {
            console.log(e.clientX+ " : " + e.clientY);
            console.log(x+  " : " + y);
            var inCircle= (e.clientX - x)*(e.clientX - x) + (e.clientY - y)*(e.clientY - y);
            console.log(inCircle);
            if ( inCircle< 2000) {
                color = " #000000";
            }
        }
    
    </script>
    <body onLoad="init();">
        <canvas id="myCanvas" width="600" height="500" style="border:10px solid"></canvas>
    

    here获取算法。

    【讨论】:

    • 也许你可以帮忙解决这个问题,它在 jsfiddle 中运行良好,但在本地无法运行。颜色没有变化。有任何想法吗?我更新了 jsfiddle 顺便说一句
    猜你喜欢
    • 1970-01-01
    • 2022-12-25
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多