移动画布弧向鼠标移动

时间:2012-07-04 20:00:06

标签: javascript jquery html5 html5-canvas

所以现在我有一个简单的canvas元素,其中的函数可以创建随机颜色,大小和弧的位置(圆圈)。

生成这些随机圆圈的随机位置的'for'循环每100毫秒执行1个圆圈(这是在onclick上完成的)。

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

http://jsfiddle.net/JXXgx/

1 个答案:

答案 0 :(得分: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处理程序。

Demo

相关问题