加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何从蛋白石调用原生javascript方法?

发布时间:2020-12-17 03:17:13 所属栏目:百科 来源:网络整理
导读:我正在编写一个基于html画布的简单游戏. 我现在正从coffeescript移植到蛋白石. 我想以有效的方式包装CanvasRenderingContext2D对象. 我目前的解决方案是一个包装器,但我真的想让这个免费的桥接器. app.rb: class Game def initialize @canvas = Element.fin
我正在编写一个基于html画布的简单游戏.
我现在正从coffeescript移植到蛋白石.

我想以有效的方式包装CanvasRenderingContext2D对象.

我目前的解决方案是一个包装器,但我真的想让这个免费的桥接器.

app.rb:

class Game
    def initialize
        @canvas = Element.find('#canvas').get(0)
        js_ctx  = `this.canvas.getContext('2d')`        # this is a javascript object
        @ctx    = CanvasRenderingContext2D.new(js_ctx)  # create the proxy
        @ctx.fillStyle='red'
        @ctx.fillRect(10,10,50,50)
    end
end

# the opal proxy class (named $CanvasRenderingContext2D in javascript space)
class CanvasRenderingContext2D
    # I currently model the proxy as a has_a while I'd prefer it to be is_a
    attr_reader :js    # the native javascript object

    def initialize(js)
        @js = js
    end

    # getter
    def fillStyle
        `this.js.fillStyle`
    end

    # setter
    def fillStyle= value
        `this.js.fillStyle= value`
    end

    # method invocation
    def fillRect x,y,width,height
        `this.js.fillRect(x,height)`
    end
end

任何提示都是受欢迎的.

解决方法

上次我使用opal时我跟着你的路径,创建了包装器,甚至直接从我的代码中直接调用了javascript.
最近我遇到了描述Native类使用的博客,所以你的代码看起来像这样:

require 'native'
class Game
  def initialize
    @canvas = Element.find('#canvas').get(0)
    @ctx  = Native(`this.canvas.getContext('2d')`)
    @ctx.fillStyle='red'
    @ctx.fillRect(10,50)
  end
end

还没有真正测试过这种方法

[1] http://dev.mikamai.com/post/79398725537/using-native-javascript-objects-from-opal

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读