我用 Python 编写了这段代码,并且在 Brython 上运行良好。 此代码在本例中旋转图像是一个齿轮。 我怎样才能改变它,以及与 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>
请您参考如下方法:
我不太熟悉 Brython,但我马上可以告诉您,要将它移植到 RapydScript,您只需删除我看到代码导入的大部分不必要的抽象,因为 RapydScript 更接近原生 JavaScript。至于在浏览器中使用 RapydScript 代码,您有几个选择:
- (推荐)提前编译你的代码并在你的 html 中包含 .js 文件(类似于 Babel、UglifyJS 等),这样代码将运行得更快并且不需要你包含编译器在页面中
- 使用浏览器内的 RapydScript 编译器(如果您不想修改编译,这似乎是最新的编译器:https://github.com/adousen/RapydScript-pyjTransformer)并将代码包含在
<script type="text/pyj">中标记与您在示例中所做的类似。
现在,假设您选择了上面推荐的选项,下一步是从代码中删除 Brython 样板,这是您的逻辑在 RapydScript 中的样子(请注意,我也对其进行了一些重构,删除了不必要的 2 -阶段旋转方法解析和不需要的 lambda 调用):
t0 = Date.now()
def rotate_property():
""" Helper function mapping user agents to transform proeprty names """
if 'Chrome' in window.navigator.userAgent: return 'webkitTransform'
elif 'Firefox' in window.navigator.userAgent: return 'MozTransform'
elif 'MSIE' in window.navigator.userAgent: return 'msTransform'
elif 'Opera' in window.navigator.userAgent: return 'OTransform'
return 'transform'
degrees = 0
def animation_step(elem_id='img1'):
""" Called every 30msec to increase the rotatation of the element. """
nonlocal degrees
# Get the right property name according to the useragent
prop = rotate_property()
# Get the element by id
el = document.getElementById(elem_id)
# Set the rotation of the element
el.style[prop] = "rotate(" + degrees + "deg)"
document.getElementById('status').innerHTML = "rotate(" + degrees + "deg)"
# Increase the rotation
degrees += 1
if degrees > 360:
# Stops the animation after 360 steps
clearInterval(tm)
degrees = 0
# Start the animation
tm = setInterval(animation_step, 30)
document.getElementById('status3').innerHTML = "Time of execution python code(" + (Date.now() - t0) + " ms)"
一些注意事项:
- 不再需要导入,RapydScript 不需要样板来与 JavaScript 交互
- Pythonic
timer.set_interval和timer.clear_interval已替换为 JavaScript 等效项(setInterval 和 clearInterval) -
document你在我的代码中看到的是 DOM 本身,document你在 Brython 中的代码是它的包装器,因此访问它的方式有点不同 - RapydScript 下降
global很久以前支持 Python 3 更安全nonlocal,这是我在代码中使用的 - 代替
time模块,RapydScript 可以直接访问 JavaScript 的Date类,我在代码中使用它来计时 - 我还建议移动
prop = rotate_property()在函数外部调用,因为用户代理不会在函数调用之间改变(在这种情况下,操作相对便宜,但对于更复杂的逻辑,这将提高您的性能) - 您似乎是通过正文从 HTML 启动 Brython
onload,摆脱它以及说<script>animation_step("img1",30);</script>的行, 上面的代码应该在页面加载时自动触发,由 setInterval 调用提供 - 由于 RapydScript 使用 unicode 字符来避免名称冲突,您需要通过将此行添加到头部来告诉 HTML 将文档视为 unicode:
<meta charset="UTF-8"> - 为了将来引用,您的
onload都没有对 RapydScript 的调用将起作用,因为与 Brython 不同,RapydScript 在其自己的范围内保护自己,对外部不可见(这长期以来一直是 JavaScript 世界公认的做法),您可以选择onload工作是:- (不推荐)用
-b编译文件标记省略 self 保护范围 - (推荐)在您的代码中,将您的函数附加到全局
window如果您希望从外部访问它们,请反对
- (不推荐)用
调用上述代码的编译版本的实际 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>
