我正在构建一个工具,其中有一个IFRAME,用户可以在其中放入包含画布动画的任何HTML。
目的是让他们选择是否要使用createJS,Adobe Edge Animate或他们喜欢的任何其他工具。
尽管如此,无论他们使用哪种工具,我都需要能够播放和暂停此画布动画。
您认为这可能吗?还是您认为我将与他们使用的框架联系在一起?
我尝试清除页面的请求动画框架,但效果不佳。
iframe.contentWindow.cancelAnimationFrame(<don't know what to put in here without accessing the animation framework>)
你有什么建议吗?
谢谢!
安德里亚
编辑:
在我的情况下,iframe是一种沙盒,用户可以在其中放置所需的任何内容,甚至包括用于他所使用框架功能的javascript
最佳答案
支持不同的Html5 Canvas库
从理论上讲是有可能的,因为尽管大多数库都有其自己的内置动画方法,但是您当然可以只使用其绘制方法,然后使用自己的动画循环为它们的图形制作动画。
但是,哇!这将是一项艰巨的任务。就在我头顶上方,您将必须:
仅加载用户选择的库的代码-例如Easel.js
。
创建一个画布DOM元素,任何库都必须使用它来显示图形。
创建一个挂钩,让他们设置自己的特定库环境。例如,在这里EaselJS用户将创建其舞台:var stage = new createjs.Stage("theRequiredCanvas");
创建一个挂钩,让他们在动画循环内运行其品牌的代码。
要将其代码挂接到框架中,必须要求他们将所有代码放入随框架一起加载的.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/