gpt4 book ai didi

javascript - 播放/暂停任何 Canvas 动画

转载 作者:行者123 更新时间:2023-12-03 09:10:14 28 4
gpt4 key购买 nike

我正在构建一个工具,其中有一个 IFRAME,用户可以在其中放置任何包含 Canvas 动画的 HTML。

目的是让他们选择是否要使用 createJS、Adobe Edge Animate 或任何其他他们喜欢的工具。

尽管如此,无论他们使用哪种工具,我都需要能够播放和暂停此 Canvas 动画。

你认为这可能吗?或者您认为我会受到他们使用的框架的束缚?

我尝试过清除页面的请求动画帧,但效果不佳。

iframe.contentWindow.cancelAnimationFrame(<don't know what to put in here without accessing the animation framework>)

你有什么建议吗?

谢谢!

安德里亚

编辑:在我的案例场景中,iframe 是一种沙箱,用户可以在其中放置任何想要的内容,甚至是用于他使用的框架功能的 javascript

最佳答案

支持不同的 Html5 Canvas 库

理论上这是可能的,因为虽然大多数库都有自己的内置动画方法,但您当然可以只使用它们的绘图方法,然后使用您自己的动画循环来为它们的绘图设置动画。

但是,哇!这将是一项艰巨的任务。我突然想到你必须:

  1. 仅加载用户选择的库的代码 - 例如。 Easel.js

  2. 创建一个 Canvas DOM 元素,任何库都必须使用它来显示绘图。

  3. 创建一个钩子(Hook)让他们设置特定的库环境。例如,这是 EaselJS 用户创建舞台的位置: var stage = new createjs.Stage("theRequiredCanvas");

  4. 创建一个钩子(Hook),让他们在您的动画循环中运行他们的代码。

  5. 要将他们的代码挂接到您的框架中,您必须要求他们将所有代码放入与您的框架一起加载的 .js 文件中。

    <

停止...!

我将不再在这里推理出解决方案,因为这对用户来说比仅仅使用他们自己的库需要更多的工作。

问题的简单部分:暂停和继续动画

您可以设置一个停止动画循环的标志。

当您想继续动画时,您可以清除该标志并请求动画循环。

示例代码:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.fillStyle='skyblue';
ctx.strokeStyle='lightgray';
ctx.lineWidth=3;
var cw=canvas.width;
var ch=canvas.height;


// animation will pause when paused==true
var paused=false;

// testing, a rotation angle for the animated rect
var angle=0;

// pause the animation on #pause click
$('#pause').on('click',function(){
paused=true;
});

// continue the animation on #continue click
$('#continue').on('click',function(){
paused=false;
requestAnimationFrame(animate);
});

// start the animation loop
requestAnimationFrame(animate);

function animate(time){
if(paused){return;}

// animate anything
ctx.clearRect(0,0,cw,ch);
ctx.translate(cw/2,ch/2);
ctx.rotate(angle);
ctx.fillRect(-50,-50,100,100);
ctx.strokeRect(-50,-50,100,100);
ctx.setTransform(1,0,0,1,0,0);

// increase the angle for the next loop
angle+=Math.PI/60;

// request another animation loop
requestAnimationFrame(animate);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='pause'>Pause</button>
<button id='continue'>Continue</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 播放/暂停任何 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097659/

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