简体   繁体   English

ruby on rails 6 - 在java脚本中动态引用图像

[英]ruby on rails 6 - referencing images dynamically in java script

I am trying to implement chessboard.js and chess.js ( https://chessboardjs.com/examples#2030 ) in the ruby on rails 6 framework and have a problem with rendering images of pieces on the chessboards (images of pieces are attached to the libraries in separate files).我正在尝试在 ruby​​ on rails 6 框架中实现 chessboard.js 和 chess.js ( https://chessboardjs.com/examples#2030 ) 并且在棋盘上呈现棋子的图像时遇到问题(附上棋子的图像到单独文件中的库)。 I added both java scripts libraries using webpacker.我使用 webpacker 添加了两个 java 脚本库。 I was trying to place the images in various places of the project but neither worked (for example ..\\img\\chesspieces\\wikipedia)我试图将图像放在项目的各个地方,但都没有奏效(例如 ..\\img\\chesspieces\\wikipedia)

I am able to render single picture separately outside of chessboard but don't know how to reference the images in the java script so that they would be displayed on the chessboard in ruby on rails 6 framework.我能够在棋盘之外单独渲染单个图片,但不知道如何在 java 脚本中引用图像,以便它们可以在 ruby​​ on rails 6 框架中显示在棋盘上。

How should I build the path to the pictures in the below java script in the ruby on rails 6 framework?我应该如何在 ruby​​ on rails 6 框架中构建以下 java 脚本中图片的路径?

JAVASCRIPT
    function pieceTheme (piece) {
      // wikipedia theme for white pieces
      if (piece.search(/w/) !== -1) {
        return 'img/chesspieces/wikipedia/' + piece + '.png'
      }
    
      // alpha theme for black pieces
      return 'img/chesspieces/alpha/' + piece + '.png'
    }
    
    var config = {
      pieceTheme: pieceTheme,
      position: 'start'
    }
    var board = Chessboard('myBoard', config)

HTML
    <div id="myBoard" style="width: 400px"></div>

THE Error example: wP.png:1 GET http://localhost:3000/images/wP.png 404 (Not Found)错误示例:wP.png:1 GET http://localhost:3000/images/wP.png 404(未找到)

I was only able to render a single picture by adding to application.js我只能通过添加到 application.js 来渲染一张图片

// import all image files in a folder:
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)

and then by adding to index.html.erb然后通过添加到 index.html.erb

  <%= image_pack_tag 'bB.png' %>

Try to Change the code尝试更改代码

const images = require.context('../images', true)

to

const images = require.context('./images', true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM