无法在轨道上应用js效果

时间:2014-08-03 06:08:25

标签: javascript ruby-on-rails ruby-on-rails-4 asset-pipeline turbolinks

我想应用简单的javascript rainydrop效果http://maroslaw.github.io/rainyday.js/demo2.html

但它不起作用。我得到了非常意外的结果,如下图所示。

我认为问题是资产管道?但我没有想法

enter image description here

这里是布局joseph_memo.html.haml

!!!
%html{lang: "en"}
  %head
    %meta{charset: "utf-8"}/
    %title rainyday.js demo #4
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true
    = javascript_include_tag 'application', 'data-turbolinks-track' => true    
    %style{media: "screen"}
      :cdata
        img { display: none; }
        body { overflow: hidden; }
        \#canvas { position: absolute; top: 0; left: 0; }
    %script{src:  asset_path("rainyday/dist/rainyday.0.1.1.min.js"), type: "text/javascript"}
    :javascript
      function run() {
        var engine = new RainyDay('canvas', 'background', window.innerWidth, window.innerHeight);
          engine.gravity = engine.GRAVITY_NON_LINEAR;
          engine.trail = engine.TRAIL_DROPS;
          engine.VARIABLE_GRAVITY_ANGLE = Math.PI / 8;
          engine.rain([
            engine.preset(0, 2, 0.5),
            engine.preset(4, 4, 1)
          ], 50);
      }

  %body{onload: "run();"}
    %img#background{alt: "background", src: asset_path("rainyday/img/city.jpg")}/
    #cholder
      %canvas#canvas

1 个答案:

答案 0 :(得分:0)

<强>布局

问题可能是由于您直接在application布局中包含了javascript。

您正在使用anonymous function(因在Rails上无法正常工作而臭名昭着),然后绑定到正文on-load事件。使用[unobtrusive] javascript 2&amp ;,你会更好地 将代码放入/app/assets/javascripts/application.js文件中:

#app/assets/javascripts/application.js
//require rainyday/dist/rainyday.0.1.1.min.js

var make_it_rain = function() {
    var engine = new RainyDay('canvas', 'background', window.innerWidth, window.innerHeight);
    engine.gravity = engine.GRAVITY_NON_LINEAR;
    engine.trail = engine.TRAIL_DROPS;
    engine.VARIABLE_GRAVITY_ANGLE = Math.PI / 8;
    engine.rain([
        engine.preset(0, 2, 0.5),
        engine.preset(4, 4, 1)
    ], 50);
};
$(document).on("page:load ready", make_it_rain);

这应该让事情有效,如果你的rain插件工作正常。我会详细介绍如何更好地构建您的应用程序,但这对于我认为的另一个答案会更好