3

所以现在我有一个简单的画布元素,它具有创建随机颜色、大小和弧(圆)位置的功能。

生成这些随机圆的随机位置的“for”循环每 100 毫秒执行 1 个圆(这是在单击时完成的)。

我想知道如何让每个圆圈慢慢靠近光标,然后跟随光标移动到任何地方。

http://jsfiddle.net/JXXgx/

4

1 回答 1

5

你可以尝试这样的事情:

var MAXIMUM_AMOUNT = 1000,
    FPS = 30,
    targetToGo,     //
    shapes = [];    //storage of circles

//Helper class
function CircleModel(x,y,r,color){
    this.x = x;
    this.y = y;
    this.r = r;   
    this.color = color; 
}
function initScene(){
    //Listening for mouse position changes
    $('canvas').mousemove(function(e){
        targetToGo.x = e.pageX;
        targetToGo.y = e.pageY;
    });
    //Circle generation timer
    var intervalID = setInterval(function(){
        if( shapes.length < MAXIMUM_AMOUNT ){
            for(var i = 0; i < 1; i++){
                //Generating random parameters for circle
                var randX = targetToGo.x - 500 + Math.floor(Math.random() * 1000);   //position x
                var randY = targetToGo.y - 300 + Math.floor(Math.random() * 600);    //position y
                var randRadius = Math.floor(Math.random() * 12);       //radius 
                var randColor = "#"+("000000"+(0xFFFFFF*Math.random()).toString(16)).substr(-6); //color
                //Adding circle to scene
                shapes.push( new CircleModel(randX,randY,randRadius,randColor) ); 
            }
        }else{
            clearInterval(intervalID);
        }
    }, 100);
    //Starts rendering timer -  
    //                  '1000' represents 1 second,as FPS represents seconds,not miliseconds
    setInterval(render,1000/FPS);
}
function render(){
    var ctx = $('canvas')[0].getContext("2d");
    var circle;
    //Clearing the scene
    ctx.clearRect(0,0,$('canvas').width(),$('canvas').height());
    //Drawing circles
    for(var i=0; i < shapes.length;++i){
        circle = shapes[i];
        //(animation part)
        //repositioning circle --
        //             (1/circle.r) is a degree of inertion,and the bigger radius,the slower it moves
        circle.x += (targetToGo.x - circle.x)*1/circle.r;   
        circle.y += (targetToGo.y - circle.y)*1/circle.r;
        ////////////////////////////////////////////
        ctx.fillStyle = circle.color;
        ctx.beginPath();
        ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fill();
    }
}

$("canvas").click(function(e){    
    targetToGo = {x: e.pageX, y:e.pageY};
    initScene();   
});

将此代码放入$(document).ready处理程序中。

演示

于 2012-07-06T08:00:19.513 回答