动画线条绘制时tweenjs的性能问题

时间:2016-02-15 15:00:02

标签: jquery canvas createjs easeljs tween.js

我正在使用eaeljs和tweenjs来动画多个线条,从一个位置通过一个点绘制到一个位置,使其成为一条曲线,并在线条的前面附加一个img。我正在使用补间插件MotionGuidePlugin。这应该发生在init() - 函数内部。没有鼠标事件或基于用户的事件会触发此事件。

我的问题是我的画布在一段时间后变得非常慢。线条变得更像“像素化”,动画会跳过很多帧 - 创建一条直线而不是曲线。我已经在Stack Overflow上研究了这个问题,并且发现这是因为为每个帧绘制了一个新的Graphics。解决方案似乎是清除图形或缓存它,但我不知道如何用我当前的代码实现它:

createjs.MotionGuidePlugin.install();

var shape = new createjs.Shape();
var bar = { x: arrowStartPosX, y: arrowStartPosY, oldx: arrowStartPosX, oldy: arrowStartPosY };
stage.addChild(shape);

var image = new createjs.Bitmap("arrow.png");
image.alpha = 0;
stage.addChild(image);

createjs.Ticker.addEventListener("tick", tick);

run();

function getMotionPathFromPoints (points) {
    console.log(points);
    var i, motionPath;
    console.log(points.length);
    for (i = 0, motionPath = []; i < points.length - 1; ++i) {
        if (i === 0) {
            motionPath.push(points[i].x, points[i].y);
        }
        else if(i === 1){
            motionPath.push(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y);
        } else {
            i++;
            motionPath.push(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y);
        }
    }
    return motionPath;
}

function run() {
    var posXStart = arrowStartPosX + 200;
    var points = [
        new createjs.Point(arrowStartPosX, arrowStartPosY),
        new createjs.Point(posXStart, middlePosY),
        new createjs.Point(arrowStartPosX, arrowEndPosY)
    ];

    createjs.Tween.get(bar).wait(timeCount-400).to({
        guide: {path: getMotionPathFromPoints(points)}
    }, 1900);

    createjs.Tween.get(image).to({rotation: -70}, 0)
    .wait(timeCount-400).to({alpha: 1}, 0)
    .to({rotation: -290, 
    guide:{ path:[startImgPosX, startImgPosY, middleImgPosX, middleImgPosY, endImgPosX, endImgPosY], 
    orient: "auto"}},1900);
}

function tick() {
    shape.graphics
    .setStrokeStyle(2, 'round', 'round')
    .beginStroke("#000000")
    .curveTo(bar.oldx, bar.oldy, bar.x, bar.y)
    .endStroke();

    bar.oldx = bar.x;
    bar.oldy = bar.y;
}

应该绘制线条,完成后,它们应该保留在原位。任何人都可以向我解释如何修复我的代码,并让Canvas再次正常运行吗?

更新

我现在为我的问题创建了一个FIDDLE。如果你在一段时间内没有做任何事情,你会看到JSFiddle网页变慢,就像我自己的网页一样。

1 个答案:

答案 0 :(得分:2)

向量可能非常昂贵,而且您的演示显示您正在添加大量的小行。每次更新舞台时,都必须重新绘制图形。 如果没有缓存,您将无法长时间执行此操作,尤其是在低功耗设备上。

根据您的最终目标,您可以缓存形状,然后在创建新内容时绘制。

// Cache up front
var shape = new createjs.Shape();
shape.cache(0,0,100,1000);

// Clear the graphics before drawing new content
shape.graphics.clear()
    .setStrokeStyle(3, 'round', 'round')
    .beginStroke("#aaa")
    .curveTo(bar.oldx, bar.oldy, bar.x, bar.y)
    .endStroke();

// Update the cache with "source-over" to just add the new content.
    shape.updateCache("source-over");
    stage.update();

这是一个小提琴更新:http://jsfiddle.net/lannymcnie/km89jbn2/2/

这种方法永远不会放慢。

干杯。

相关问题