我正在编写一个基于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,y,width,height)`
end
end
Run Code Online (Sandbox Code Playgroud)
任何提示都是受欢迎的.
上次我使用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,10,50,50)
end
end
Run Code Online (Sandbox Code Playgroud)
还没有真正测试过这种方法
[1] http://dev.mikamai.com/post/79398725537/using-native-javascript-objects-from-opal
| 归档时间: |
|
| 查看次数: |
1120 次 |
| 最近记录: |