【问题标题】:Simple image rotation with Python and DOM using RapydScript使用 RapydScript 使用 Python 和 DOM 进行简单的图像旋转
【发布时间】:2016-09-25 17:07:28
【问题描述】:

我用 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>

【问题讨论】:

    标签: python rapydscript


    【解决方案1】:

    我对 Brython 不太熟悉,但我可以立即告诉您,要将其移植到 RapydScript,您只需删除我看到的代码导入的大部分不必要的抽象,因为 RapydScript 更接近原生 JavaScript。至于在浏览器中拥有 RapydScript 代码,您有几个选择:

    • (推荐)提前编译你的代码并在你的html中包含.js文件(类似于Babel,UglifyJS等),这样代码运行速度会更快,并且不需要你包含编译器在页面中
    • 使用浏览器内的 RapydScript 编译器(如果您不想修改编译,这似乎是最新的:https://github.com/adousen/RapydScript-pyjTransformer)并将代码包含在 &lt;script type="text/pyj"&gt; 标签中,类似于你已经在示例中完成了。

    现在,假设您选择了上面推荐的选项,下一步是从代码中删除 Brython 样板,这是您的逻辑在 RapydScript 中的样子(请注意,我还对其进行了一些重构,删除了不必要的 2 -stage 旋转方法解析和不需要的 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_intervaltimer.clear_interval 已替换为 JavaScript 等效项(setInterval 和 clearInterval)
    • document 你在我的代码中看到的是 DOM 本身,document 你在 Brython 代码中是一个包装器,因此访问它的工作方式有点不同
    • RapydScript 很久以前就放弃了 global,转而支持 Python 3 更安全的 nonlocal,这是我在代码中使用的替代方式
    • RapydScript 可以直接访问 JavaScript 的 Date 类,而不是 time 模块,我在代码中使用它来计时
    • 我还建议将 prop = rotate_property() 调用移到函数之外,因为用户代理不会在函数调用之间更改(在这种情况下,操作相对便宜,但对于更复杂的逻辑,这将提高您的性能)李>
    • 你似乎是通过正文onload 从 HTML 启动 Brython,去掉它以及上面写着 &lt;script&gt;animation_step("img1",30);&lt;/script&gt; 的行,上面的代码应该会在页面加载时自动触发,由 setInterval 调用提供
    • 由于 RapydScript 使用 unicode 字符来避免名称冲突,因此您需要通过添加以下行来告诉 HTML 将文档视为 unicode:&lt;meta charset="UTF-8"&gt;
    • 供将来参考,您对 RapydScript 的任何onload 调用都不起作用,因为与 Brython 不同,RapydScript 在其自己的范围内保护自己,对外部不可见(这在 JavaScript 世界中已被接受很长时间了) ,使onload 工作的选项是:
      • (不推荐)编译带有-b标志的文件以省略自我保护范围
      • (推荐)在您的代码中,如果您希望从外部访问它们,请将您的函数附加到全局 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>
    

    【讨论】:

    • 完美运行!
    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多