【问题标题】:Using p5.js with F# Fable将 p5.js 与 F# Fable 一起使用
【发布时间】:2018-06-04 18:28:42
【问题描述】:

我正在尝试使用 F# Fable 和 p5.js 创建一个网页。我正确声明了 setupdraw 函数,并且在 HTML 中引用了 p5.js。但是似乎没有任何效果:永远不会调用 setup 函数,因此永远不会创建 canvas。不显示错误信息。

以下是我正在使用的代码。


<!doctype html>
<html>
<head>
  <style>
    body {
        padding: 20px;
        margin: 0 auto;
    }
    canvas {
        vertical-align: top;
    }
    div {
        margin-bottom: 20px;
    }
  </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

  <title>Simple Fable App</title>
  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" href="fable.ico" />
</head>
<body>

</body>
</html>

open Fable.Core
open Fable.Core.JsInterop
open Fable.Import

[<Emit("fill($0)")>]
let fill (_: int): unit = jsNative

[<Emit("rect($0, $1, $2, $3)")>]
let rect (_: int) (_: int) (_: int) (_: int): unit = jsNative

[<Emit("frameRate($0)")>]
let frameRate (_: int): unit = jsNative

[<Emit("createCanvas($0, $1)")>]
let createCanvas (_: int) (_: int): unit = jsNative

let setup () =
    createCanvas 500 500
    frameRate 15

let draw () =
    fill 255
    rect 10 10 100 101

如果我将上面相同的 HTML 与等效的 JS 一起使用,它将按预期工作,所以我认为 Fable 搞砸了我的某个地方。

<!doctype html>
<html>
<head>
  <style>
    body {
        padding: 20px;
        margin: 0 auto;
    }
    canvas {
        vertical-align: top;
    }
    div {
        margin-bottom: 20px;
    }
  </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

  <title>Simple Fable App</title>
  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" href="fable.ico" />
</head>
<body>

</body>

<script>
function setup () {
    createCanvas(500, 500)
    frameRate(15)
}

function draw () {
    fill(255)
    rect(10, 10, 100, 101)
}

</script>
</html>

【问题讨论】:

  • setupdraw 函数是在一个模块中编译的,而不是像在 JS 中声明的那样全局编译。

标签: f# p5.js fable-f#


【解决方案1】:

按照@FyodorSoikin 给出的提示,我搜索了文档并找到了how to add properties to JS objects

所以我将两个相关函数添加到Browser.window 对象(即使它们成为全局对象):

Browser.window?setup <- setup
Browser.window?draw <- draw

现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多