Drawing on a “dynamic” canvas

问题: So I have a loop that creates canvas according to certain parameters from jquery. Here's the code: var Game = { cards: [], $board: $('[data-display="game-board"]'...

问题:

So I have a loop that creates canvas according to certain parameters from jquery. Here's the code:

var Game = {
    cards: [],
    $board: $('[data-display="game-board"]'),

    deal: function() {
     var self = this;
     var dealRequest = $.ajax({
        url: 'set.php?action=deal',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            self.cards = data;
            self.displayCards.call(self);
            self.existingSet(data);
            self.setCardListeners();
            self.setPageListeners();
        }
     });
   },

    displayCards: function() {
     var self = this;
     $.each(this.cards, function(index, card) {
       var cardNode = $('<div>');
       cardNode.addClass('card');
       $(cardNode).data({
         'id': card.id,
         'shape': card.shape,
         'fill': card.fill,
         'color': card.color,
         'number': card.number
       });
     
   var shapeNode = $("<canvas></canvas>");
   shapeNode.addClass('shape ' + card.color + ' ' + card.shape + ' ' + card.fill);

   for (var i = 0; i < card.number; i++) {
     cardNode.append(shapeNode.clone());
   }
   self.$board.append(cardNode);
    
   // display 4 cards per row
   if ((index+1) % 3 === 0) {
    self.$board.append($('<div>'));
   }
};

Then I try to recover from my HTML these canvas created using the name of the css classes, with something like:

var canvases = document.getElementsByClassName('shape diamond red solid');

But when I try to draw in these canvas there is nothing displayed. I do something like:

var canvases = document.getElementsByClassName('shape red diamond solid');
for (let canvas of canvases) {
    var context = canvas.getContext('2d');
    drawDiamond(context, 50, 50, 75, 100);
    canvas.fillStyle("#FF0000");
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

But when I create a canvas statically that works.

Can you please try to help me to find the problem or maybe a solution? Thank you!


回答1:

Would suggest the following code:

$.each(this.cards, function(index, card) {
  var cardNode = $('<div>', {
    class: "card"
  }).appendTo("body");
  cardNode.data(card);
  var shapeNode = $('<canvas>', {
    class: "shape " + card.color + " " + card.shape + " " + card.fill
  }).appendTo(cardNode);
});

The once that is done the following should work:

var canvases = $('.shape.red.diamond.solid');

canvases.each(function(i, c) {
    var context = c.getContext('2d');

    drawDiamond(context, 50, 50, 75, 100);
    c.fillStyle("#FF0000");
    ctx.fillRect(0, 0, c.width, c.height);
});

Update

Your example is more thorough yet it is not a Minimal, Reproducible Example. Consider the following.

var Game = {
  cards: [],
  $board: $('[data-display="game-board"]'),
  deal: function() {
    var self = this;
    /*
    $.getJSON('set.php?action=deal', function(data) {
      $.each(data, function(i, card) {
        self.cards.push(card);
      });
      self.displayCards();
      self.existingSet(data);
      self.setCardListeners();
      self.setPageListeners();
    });
    */
    self.cards.push({
      id: "ace-spade",
      shape: "spade",
      fill: "solid",
      color: "black",
      number: 1
    });
    self.displayCards();
  },
  displayCards: function() {
    var self = this;
    if (self.cards.length == 0) {
      return false;
    }
    $.each(self.cards, function(index, card) {
      var cardNode = $('<div>', {
        class: "card"
      }).appendTo(self.$board);
      cardNode.data({
        'id': card.id,
        'shape': card.shape,
        'fill': card.fill,
        'color': card.color,
        'number': card.number
      });

      for (var i = 0; i < card.number; i++) {
        cardNode.append($("<canvas>", {
          class: 'shape ' + card.color + ' ' + card.shape + ' ' + card.fill
        }));
      }
      self.$board.append(cardNode);

      // display 4 cards per row
      if ((index + 1) % 3 === 0) {
        self.$board.append($('<div>'));
      }
    });
  }
};

Game.deal();
.card {
  border: 1px solid #000;
  border-radius: 6px;
  width: 100px;
  height: 175px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-display="game-board"></div>

I cannot test with AJAX, so I populated the "deck" with an Ace of Spades. The resulting HTML is:

<div data-display="game-board">
  <div class="card">
    <canvas class="shape black spade solid"></canvas>
  </div>
</div>

You will need to test further in your own code. Update your question further if needed.

  • 发表于 2020-06-27 19:18
  • 阅读 ( 121 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除