使用 RapydScript Python 和 DOM 的简单图像旋转
Simple image rotation with Python and DOM using RapydScript
我在 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 等),这样代码会 运行 快得多并且不需要您在页面中包含编译器
- 使用 in-browser RapydScript 编译器(如果您不想修改编译,这似乎是最 up-to-date: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 本身,你在 Brython 代码中看到的 document
是它的包装器,因此访问它的方式有点不同
- RapydScript 很久以前就放弃了
global
支持 Python 3 更安全 nonlocal
,这是我在代码中使用的
- 而不是
time
模块,RapydScript 可以直接访问 JavaScript 的 Date
class,我在代码中使用它来计时
- 我还建议将
prop = rotate_property()
调用移动到函数外部,因为用户代理不会在函数调用之间改变(在这种情况下,操作相对便宜,但对于更复杂的逻辑,这将提高您的性能)
- 您似乎是通过 body
onload
从 HTML 启动 Brython,删除它以及 <script>animation_step("img1",30);</script>
行,上面的代码应该页面加载后自动触发 setInterval 调用
- 由于 RapydScript 使用 unicode 字符来避免名称冲突,您需要告诉 HTML 通过将此行添加到标题来将文档视为 unicode:
<meta charset="UTF-8">
- 供将来参考,none 对 RapydScript 的
onload
调用将起作用,因为与 Brython 不同,RapydScript 在其自身范围内保护自己,对外部不可见(这是公认的做法在 JavaScript 世界中很长一段时间),使 onload
工作的选项是:
- (不推荐)使用
-b
标志编译文件以省略 self-protecting 范围
- (推荐)在你的代码中,将你的函数附加到全局
window
object 如果你想从外部访问它们
调用上述代码的编译版本的实际 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>
我在 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 等),这样代码会 运行 快得多并且不需要您在页面中包含编译器
- 使用 in-browser RapydScript 编译器(如果您不想修改编译,这似乎是最 up-to-date: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 本身,你在 Brython 代码中看到的document
是它的包装器,因此访问它的方式有点不同- RapydScript 很久以前就放弃了
global
支持 Python 3 更安全nonlocal
,这是我在代码中使用的 - 而不是
time
模块,RapydScript 可以直接访问 JavaScript 的Date
class,我在代码中使用它来计时 - 我还建议将
prop = rotate_property()
调用移动到函数外部,因为用户代理不会在函数调用之间改变(在这种情况下,操作相对便宜,但对于更复杂的逻辑,这将提高您的性能) - 您似乎是通过 body
onload
从 HTML 启动 Brython,删除它以及<script>animation_step("img1",30);</script>
行,上面的代码应该页面加载后自动触发 setInterval 调用 - 由于 RapydScript 使用 unicode 字符来避免名称冲突,您需要告诉 HTML 通过将此行添加到标题来将文档视为 unicode:
<meta charset="UTF-8">
- 供将来参考,none 对 RapydScript 的
onload
调用将起作用,因为与 Brython 不同,RapydScript 在其自身范围内保护自己,对外部不可见(这是公认的做法在 JavaScript 世界中很长一段时间),使onload
工作的选项是:- (不推荐)使用
-b
标志编译文件以省略 self-protecting 范围 - (推荐)在你的代码中,将你的函数附加到全局
window
object 如果你想从外部访问它们
- (不推荐)使用
调用上述代码的编译版本的实际 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>