日期:2014-05-16  浏览次数:20307 次

canvas动画效果..高手指点
已经在canvas画布上画出了类似九宫格的形状:
现在想这九个小方块按照设定的轨迹移动最后定格。轨迹没有写 我想知道是怎么样的步骤。。。
贴出代码:
JScript code

function getCursorPosition(e){
    var x;
    var y;
    if (e.pageX != undefined && e.pageY != undefined) {
    x = e.pageX;
    y = e.pageY;
    }else{
        //the position relativeto the docment
        x = e.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
    y = e.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
    }
    //coordiantes to the canvas
    var c = document.getElementById("logo");
    x -= c.offsetLeft;
    y -= c.offsetTop;
    
    //if the mouse position 
    if(x>=368 && x<=400 && y>=10 && y<=50){
        c_context = c.getContext("2d");
        //there have a block box to discovery the text "H"
        c_context.fillStyle = "#323232";
        c_context.beginPath();
        c_context.moveTo(368,10);
        c_context.lineTo(400,10);
        c_context.lineTo(400,50);
        c_context.lineTo(368,50);
        c_context.fill();
        
        //there have nine orange box instead if the text "H"
        c_context.fillStyle = "#f99405";
        for(i = 370 ;i<411; i+=14){
          for(j=10; j<51;j+=14){
                c_context.beginPath();
                c_context.moveTo(i,j);
                c_context.lineTo(i+13,j);
                c_context.lineTo(i+13,j+13);
                c_context.lineTo(i,j+13);
                c_context.fill();
                //the boxes move to anywhere they want
                //这里是想加的代码 但不知道怎么写。(每画出一个小方块就按照预定的轨迹移动)

            }
        }
        
        
        
    }
}


这个方法的是根据鼠标在canvas上的坐标来判断是否执行小方块的运动轨迹

------解决方案--------------------
动画其实就是一帧一帧的画面,也就是说,你需要用js不停的修改画布,就行了。

参考:https://developer.mozilla.org/cn/Canvas_tutorial/Basic_animations

------解决方案--------------------
你可以考虑将你的小方块设计为一个类,然后9个小方块就是9个对象,每个对象都有x,y记录当前的坐标,然后计算出下一步会移动哪个坐标,然后将小方块擦掉,绘制到下一个坐标上.可以参考我写的俄罗斯方块中的Rect类http://topic.csdn.net/u/20120211/00/a6595ac9-2d18-49ad-9e6d-5cf63db0eb05.html?33121