如何在Javascript中实现随机图像?

时间:2017-09-17 22:10:46

标签: javascript html

在一些帮助下,我现在有一个程序,它给我一个随机的扑克牌顺序。

现在我希望我的程序以特定的随机顺序向我显示这些卡的图像。 我已按行列和套装命名文件夹和图像,告诉程序要使用哪个图像,但由于某种原因,它无法正常工作。

这是我的HTML和Javascript代码:



var deck = [];

function setCards(){
  var suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
  var ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "Ten", "Jack", "Queen", "King"];
  
  suits.forEach(function(suit){
     ranks.forEach(function(rank){
      var card = {};
      card.suit = suit;
      card.rank = rank;
      deck.push(card);
     });
      
    });
}

function newCard(count) {
  var remainingCards = 52 - count;
  var index = Math.floor(Math.random() * remainingCards);
  var card= deck[index];
  deck.splice(index,1);
  return card;
 }

function dealCards() {
  document.getElementById('hand').innerHTML = '<dt> Deck </dt>';
  setCards();
  
  for (var i = 0; i < 52; i++) {
  var card = newCard(i);
  document.getElementById('hand').innerHTML += new Image(335, 442);

  card.src = '/Game/'card.rank'/'card.suit'.png';
  }
}
&#13;
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="CardGame.js"></script>
    <link rel="stylesheet" type="text/css" href="CardGame.css">
</head>
<body>
    <button type="button" onclick="dealCards()">Shuffle Deck</button>
    <hr/> 
    <img id = "hand">
</body>
</html>
&#13;
&#13;
&#13;

我的文件夹中包含西装的名称和排名的图像。 对你而言,我的代码可能显而易见,但我无法看到它。 如果你弄错了,可以告诉我吗?

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。首先,您需要正确连接图像src字符串'/Game/' + card.rank + '/' + card.suit + '.png';您还必须使用appendChild()正确插入图像

看看这个工作示例:

&#13;
&#13;
var deck = [];

function setCards(){
  var suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
  var ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "Ten", "Jack", "Queen", "King"];
  
  suits.forEach(function(suit){
     ranks.forEach(function(rank){
      var card = {};
      card.suit = suit;
      card.rank = rank;
      deck.push(card);
     });
      
    });
}

function newCard(count) {
  var remainingCards = 52 - count;
  var index = Math.floor(Math.random() * remainingCards);
  var card= deck[index];
  deck.splice(index,1);
  return card;
 }

function dealCards() {
  document.getElementById('hand').innerHTML = '<dt> Deck </dt>';
  setCards();
  
  for (var i = 0; i < 52; i++) {
  var card = newCard(i);
  var img = new Image(335, 442);
  img.src = '/Game/' + card.rank + '/' + card.suit + '.png';
  img.alt = card.rank + ' of ' + card.suit;
  document.getElementById('hand').appendChild(img);

  }
}
&#13;
img {
  display: inline-block;
}
&#13;
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="CardGame.js"></script>
    <link rel="stylesheet" type="text/css" href="CardGame.css">
</head>
<body>
    <button type="button" onclick="dealCards()">Shuffle Deck</button>
    <hr/> 
    <div id = "hand"></div>
</body>
</html>
&#13;
&#13;
&#13;