如何使用TweenJS为EaselJS渐变设置动画? [英] How to animate an EaselJS gradient using TweenJS?

查看:217
本文介绍了如何使用TweenJS为EaselJS渐变设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的渐变:

var graphic = new createjs.Graphics().beginLinearGradientFill(
  ["#000", "#fff", "#000"],
  [0, 0.5, 1],
  0, 0,
  window.innerWidth, window.innerHeight
).drawRect(0, 0, window.innerWidth, window.innerHeight);
var shape = new createjs.Shape(graphic);

我将如何为渐变设置动画,使其看起来好像在移动? (即,如果这是CSS制造的,则background-position会慢慢改变)

How would I animate the gradient so that it appears to be moving? (i.e. if this were CSS-made, the background-position would slowly change)

推荐答案

不幸的是,画布渐变不像CSS那样简单.您必须在每次更改渐变命令时重新构建它.

Unfortunately Canvas gradients are not as simple to animate as CSS. You have to rebuild the gradient command any time it changes.

尽管它需要最新的Nween版本的TweenJS,但我构建了一个可以简化此操作的快速演示,该版本具有出色的ColorPlugin,可以为色标设置动画.

I built a quick demo that can facilitate this, though it requires the most recent NEXT version of TweenJS, which has a great ColorPlugin for animating the color stops.

http://jsfiddle.net/lannymcnie/uhqake7e/ 更新:更简单的方法 http://jsfiddle.net/uhqake7e/2/

http://jsfiddle.net/lannymcnie/uhqake7e/ UPDATE: Easier approach http://jsfiddle.net/uhqake7e/2/

关键部分:

var colors = ["#ff0000", "#0000ff"],
    ratios = [0,1],
    w = 120, h = 120, // Shape dimensions
    x0 = 0, y0 = 0, x1 = 0, y1 = h; // Gradient dimensions

// Create shape

var shape = new createjs.Shape()
        .set({color1: colors[0], color2: colors[1]}); // Set initial color values
// Do the fill, and store the command for later
var fillCommand = shape.graphics.beginLinearGradientFill(colors, ratios, x0, y0, x1, y1).command;

有关命令的更多信息,请参见本文.

For more on commands, check out this article.

然后我们可以补间颜色值:

Then we can tween the color values:

var tween = createjs.Tween.get(shape, {bounce:true, loop:true})
    .to({color1:"#00ff00", color2:"#ff00ff"}, 1000);

最后,在更改时重新构建渐变: [更新:更简单的方法]

And lastly, rebuild the gradient on change: [UPDATED: Simpler approach]

tween.on("change", function(event) {
    fillCommand.linearGradient([shape.color1, shape.color2], ratios, x0, y0, x1, y1);
}

一种类似的方法是使用补间色,并仅重绘形状的内容,但这将需要您存储所有指令.此示例更新了用于渐变"的实际命令.

A similar approach would be to use the color tween, and just redraw the shape's contents, but it would require you to store ALL the instructions. This sample updates the actual command used for the Gradient.

太糟糕了,这有点令人费解,尤其是因为CSS非常简单:)

It is too bad this has to somewhat convoluted, especially since CSS is so simple :)

干杯.

这篇关于如何使用TweenJS为EaselJS渐变设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆