使用RapydScript使用Python和DOM进行简单的图像旋转

使用RapydScript使用Python和DOM进行简单的图像旋转,python,rapydscript,Python,Rapydscript,我用Python编写了这段代码,可以很好地与Brython配合使用。 此代码在本例中旋转一个cog图像。 如何更改它,以及使用RapydScript需要做哪些更改?我是编程新手,请耐心等待:D <!DOCTYPE html> <html> <head> <!-- load Brython --> <script src="http://brython.info/src/brython_dist.js"></script>

我用Python编写了这段代码,可以很好地与Brython配合使用。 此代码在本例中旋转一个cog图像。 如何更改它,以及使用RapydScript需要做哪些更改?我是编程新手,请耐心等待:D

<!DOCTYPE html>
<html>
<head>

<!-- load Brython -->
<script src="http://brython.info/src/brython_dist.js"></script>


<!-- the main script; after loading, Brython will run all 'text/python3' scripts -->
<script type='text/python'>
from browser import window, timer, document, html
import time

<!-- I know that here, I must use this t0 = Date.now() -->

t0 = time.time()


def user_agent():
   """ Helper function for determining the user agent """
   if window.navigator.userAgent.find('Chrome'):
       return 'chrome'
   elif window.navigator.userAgent.find('Firefox'):
       return 'firefox'
   elif window.navigator.userAgent.find('MSIE'):
       return 'msie'
   elif window.navigator.userAgent.find('Opera'):
       return 'opera'

# Dict Mapping UserAgents to Transform Property names
rotate_property = {
   'chrome':'WebkitTransform',
   'firefox':'MozTransform',
   'msie':'msTransform',
   'opera':'OTransform'
}

degrees = 0
def animation_step(elem_id):
   """ Called every 30msec to increase the rotatation of the element. """
   global degrees, tm

   # Get the right property name according to the useragent
   agent = user_agent()
   prop = rotate_property.get(agent,'transform')

   # Get the element by id
   el = document[elem_id]

   # Set the rotation of the element
   setattr(el.style, prop, "rotate("+str(degrees)+"deg)")
   document['status'].innerHTML = "rotate("+str(degrees)+" deg)"


   # Increase the rotation
   degrees += 1
   if degrees > 360:
       # Stops the animation after 360 steps
       timer.clear_interval(tm)
       degrees = 0

# Start the animation
tm = timer.set_interval(lambda id='img1':animation_step(id),30)

document['status3'].innerHTML = "Time of execution python code("+str(time.time()-t0)+" ms)"

<!-- I know that here i must use this: "Time of execution python code", Date.now()-t0, "ms") -->
</script>

</head>

<!-- After the page has finished loading, run bootstrap Brython by running
     the Brython function. The argument '1' tells Brython to print error
     messages to the console. -->
<body onload='brython(1)'>

<img id="img1" src="cog1.png" alt="cog1">
<script>animation_step("img1",30);</script>
<h2 style="width:200px;" id="status"></h2>
<h2 style="width:800px;" id="status3"></h2>


</body>  
</html>

从浏览器导入窗口、计时器、文档、html
导入时间
t0=时间。时间()
def user_agent():
“”“确定用户代理的助手函数”“”
如果window.navigator.userAgent.find('Chrome'):
返回“chrome”
elif window.navigator.userAgent.find('Firefox'):
返回“firefox”
elif window.navigator.userAgent.find('MSIE'):
返回“msie”
elif window.navigator.userAgent.find('Opera'):
返回“歌剧”
#Dict映射UserAgent以转换属性名称
旋转_属性={
“chrome”:“WebKittTransform”,
“firefox”:“MozTransform”,
'msie':'msTransform',
《歌剧》:《奥特兰斯福》
}
度=0
定义动画步骤(元素id):
“”“每30毫秒调用一次以增加元素的旋转。”“”
全球学位
#根据useragent获取正确的属性名称
代理=用户\代理()
prop=rotate\u属性.get(代理,'transform')
#按id获取元素
el=文件[elem_id]
#设置元素的旋转
setattr(el.样式,道具,“旋转”(+str(度)+“度)”)
document['status'].innerHTML=“旋转(“+str(度)+”deg)”
#增加旋转
度+=1
如果角度>360度:
#360步后停止动画
定时器清除间隔(tm)
度=0
#启动动画
tm=timer.set_interval(lambda id='img1':动画步骤(id),30)
document['status3'].innerHTML=“python代码的执行时间(“+str(Time.Time()-t0)+”ms)”
动画步骤(“img1”,30);

我对Brython不太熟悉,但我可以马上告诉您,要将其移植到RapydScript,只需删除我看到的代码导入的大部分不必要的抽象,因为RapydScript更接近本机JavaScript。至于在浏览器中使用RapydScript代码,您有两个选项:

  • (推荐)提前编译代码,并在html中包含.js文件(类似于Babel、UglifyJS等),这样代码运行速度会快得多,并且不需要在页面中包含编译器
  • 使用浏览器中的RapydScript编译器(如果您不想修改编译,则此编译器似乎是最新的:),并将代码包含在
    标记中,类似于您在示例中所做的操作
现在,假设您选择上面推荐的选项,下一步是从代码中删除Brython样板文件,以下是您的逻辑在RapydScript中的样子(请注意,我还对其进行了一些重构,删除了不必要的两阶段旋转方法解析和不必要的lambda调用):

需要注意的几点:

  • 不再需要导入,RapydScript不需要样板文件与JavaScript交互
  • Pythonic
    timer.set\u interval
    timer.clear\u interval
    已被JavaScript等价物(setInterval和clearInterval)替换
  • document
    您在我的代码中看到的是DOM本身,
    document
    您在Brython代码中看到的是围绕它的包装器,因此访问它的方式有点不同
  • RapydScript很久以前就放弃了
    global
    ,转而支持python3更安全的
    非本地的
    ,这正是我在代码中使用的
  • RapydScript可以直接访问JavaScript的
    Date
    类,而不是
    time
    模块,我在代码中使用它来计时
  • 我还建议将
    prop=rotate\u property()
    调用移到函数外部,因为用户代理不会在函数调用之间更改(在这种情况下,操作相对便宜,但对于更复杂的逻辑,这将提高性能)
  • 您似乎是通过body
    onload
    从HTML启动Brython,摆脱这一点以及说
    animation\u步骤(“img1”,30)的行,通过setInterval调用,一旦页面加载,上述代码将自动触发
  • 由于RapydScript使用unicode字符来避免名称冲突,因此需要告诉HTML将文档作为unicode处理,方法是将以下行添加到标题:
  • 作为将来的参考,您对RapydScript的
    onload
    调用都不会起作用,因为与Brython不同,RapydScript在自己的范围内保护自己,对外不可见(这在JavaScript世界中已经是公认的做法很长时间了),您可以选择使
    onload
    起作用:
    • (不推荐)使用
      -b
      标志编译文件以忽略自我保护范围
    • (推荐)在代码内部,如果希望从外部访问函数,请将函数附加到全局
      窗口
      对象
调用上述代码编译版本的实际html代码如下所示:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<img id="img1" src="cog1.png" alt="cog1">
<h2 style="width:200px;" id="status"></h2>
<h2 style="width:800px;" id="status3"></h2>
<script src="myfile.js"></script>
</body>
</html>

工作完美!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<img id="img1" src="cog1.png" alt="cog1">
<h2 style="width:200px;" id="status"></h2>
<h2 style="width:800px;" id="status3"></h2>
<script src="myfile.js"></script>
</body>
</html>