0
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8' />
    <title>Game 1</title>
</head>
<body>
    <canvas id ='myCanvas' height="400" width="600"></canvas>
    <div id='pos'>Pos:x,y</div>
    <div id='number'>00</div>
    <input  type='button' id='btn' value='Clear' OnClick="clearB()" class='button' />
</body>
</html>
<script type='text/javascript'>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    Balls = [];
    colors = ['#00000','#FD0006'];


        canvas.addEventListener("mousemove",click,false);
        function click(event){
            var i;
            document.getElementById('pos').innerHTML = 'x:' +event.pageX + ' y:'+event.pageY; 
            ctx.clearRect(0,0,canvas.width,canvas.height);
            for(var i=0;i<Balls.length;i++){ 
                difx = Balls[i].x - event.pageX; 
                dify = Balls[i].y - event.pageY;
                dist = Math.sqrt(difx*difx + dify*dify);

                if(dist  <  Balls[i].r ){
                    document.getElementById('number').innerHTML = 'n:' + i;
                    Balls[i].c = colors[1];
                    Balls[i].draw();
                }else{
                    Balls[i].c = colors[0];
                    Balls[i].draw();

                }

            }
        }


        /* declarando estrutura */
        Ball = function(){
            this.x = 0;
            this.y = 0;
            this.r = 0;
        };
        Ball.pt = Ball.prototype;
        /* func para iniciar valores */ 
        Ball.pt.init = function(px,py){
            this.x = px;
            this.y = py;
            this.r = 20;
            this.c = colors[0];
        }
        Ball.pt.draw = function(){
            ctx.beginPath();
            ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
            ctx.closePath();
            ctx.fillStyle = this.c;
            ctx.fill();
        }
        function create(color){
            for(var i= 0;i < 10;i++){
                for(var j=0;j<30;j++){
                    b = new Ball();
                    b.init(20+j*40,20+i*40);
                    b.draw();
                    Balls.push(b);

                }
            }
        }
        function clearB(){
            for(var i=0;i<Balls.length;i++)
                Balls.pop();
            create();
        }

        create(); 


</script>

嘿伙计们,请帮助我!在我设置 Balls[i].c = colors[1] 之后,ctx.fillStyle 不再改变颜色,我真的不知道为什么.. 代码没有错,因为我可以随时改变颜色,但是当mousemove 侦听器已激活我无法更改颜色,所以我认为问题出在 mousemove 事件中。

4

1 回答 1

0

我不完全确定你想让上面的代码做什么,但是你的基本问题是你的颜色初始化:

这在黑色的颜色值中缺少一个字符:

colors = ['#00000','#FD0006'];

应该:

colors = ['#000000', '#FD0006'];

Demo Fiddle

于 2013-09-13T23:40:08.947 回答