gpt4 book ai didi

javascript - 如何在 Canvas 上制作线条动画

转载 作者:行者123 更新时间:2023-11-28 07:30:32 26 4
gpt4 key购买 nike

我正在尝试使用 Canvas 为线条设置动画。我想使用 TimelineLite 来处理动画。我该怎么做?我知道在 TimelineLite 中,时间线看起来像这样:

var timeline = new TimelineLite();
timeline.to(target, duration, vars, position);

这些点存在于 JSON 文件中,并且该文件已通过 AJAX 正确引入。我希望该线从点 x1 和 y1 开始,保持 x2 为相同值,并将其动画到 y2 位置。所以我基本上希望它从 x1-y1 增长到 x2-y2。

JS

function animateLines(name, stroke, width, x1, y1, x2, y2){
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineWidth = width;
ctx.strokeStyle = stroke;
ctx.stroke;
console.log(x2);
}

for(var i = 0; i < animated_lines.length; i++){
animateLines(animated_lines[i].name, animated_lines[i].stroke, animated_lines[i].width, animated_lines[i].x1, animated_lines[i].y1, animated_lines[i].x2, animated_lines[i].y2);
}

JSON

"animated_lines": [
{
"name": "Test",
"stroke": "red",
"width": 3,
"x1": 0,
"y1": 0,
"x2": 0,
"y2": 50
}
]

所以我的问题实际上是一个多部分的问题。如何使用 Canvas 对线条进行动画处理?如何根据 animateLine() 函数中的name 为线条设置动画?

最佳答案

TimelineLite 使用元素 转换该元素的目标值。

您可以使用 onUpdate 随着时间的推移观察转换的更新进度,并根据该值对线条进行动画处理。

timeline.eventCallback('onUpdate',function(data){
var progress = this.progress();
// Do animation calls here!
});

这是一个工作示例代码片段

我正在时间轴期间转换 Canvas 不透明度并对 Canvas 进行动画处理。

var timeline = new TimelineLite();
var mainCanvas = document.getElementById("ctx");
var ctx = mainCanvas.getContext("2d");
var temp = document.createElement('div');

var animated_lines = [{
"name": "Red",
"stroke": "#ff0000",
"width": 3,
"x1": 50,
"y1": 50,
"x2": 100,
"y2": 100
},{
"name": "Green",
"stroke": "#00ff00",
"width": 2,
"x1": 50,
"y1": 20,
"x2": 100,
"y2": 100
}];

function createLine(line, progress) {
ctx.lineWidth = line.width;
ctx.strokeStyle = line.stroke;
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2*progress);
ctx.stroke();
}

console.log('ctx', ctx);
timeline.from('#ctx', 10, { opacity: 0 });

timeline.eventCallback('onUpdate',function(){
var progress = this.progress();
//console.log(progress);
ctx.clearRect ( 0 , 0 , mainCanvas.width, mainCanvas.height );
for (var i = 0; i < animated_lines.length; i++) {
createLine(animated_lines[i], progress);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<canvas id="ctx" />

关于javascript - 如何在 Canvas 上制作线条动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com