问题
I've got a gradient like so:
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);
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)
回答1:
Unfortunately Canvas gradients are not as simple to animate as CSS. You have to rebuild the gradient command any time it changes.
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/ UPDATE: Easier approach http://jsfiddle.net/uhqake7e/2/
The key pieces:
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.
It is too bad this has to somewhat convoluted, especially since CSS is so simple :)
Cheers.
来源:https://stackoverflow.com/questions/45904556/how-to-animate-an-easeljs-gradient-using-tweenjs