-2

I'm struggling to get an image of a deck of small cards into spritesheet form using javascript. I need to get them into an array so as to shuffle them. Here's what I've got so far. Only the canvas shows up light blue against a dark blue background.

enter image description here

<html>
  <head>
    <style>
      canvas#game-canvas {
        position: absolute;
        top: 5%;
        left: 5%;
        background: lightblue;
        height: 281px;
        width: 500px;
      }
      body {
        background: darkblue;
      }    
    </style>
    <script type="text/javascript" src="jquery1_10_2_min.js"></script>
    <script>
      var canvas = document.getElementById("game-canvas");
      var ctx = canvas.getContext("2d");

      function SpriteSheet(path, frameWidth, frameHeight) {

         this.image = new Image();
         this.frameHeight = frameHeight;
         this.frameWidth = frameWidth;


         // calculate the number of frames in a row after the image loads
         var self = this;
         this.image.onload = function() {
            self.framesPerRow = Math.floor(this.image.width / frameWidth);
         };

         this.image.src = path;

      }

      var spritesheet = new SpriteSheet('small_playing_cards.png', 54, 65);   
    </script>

  </head>
  <body>
    <canvas id="game-canvas"></canvas>
  </body>
</html>
listenlight
  • 654
  • 1
  • 12
  • 27
  • What you exactly want to do? PS: you're not drawing the image also, and it's missing the area x & y of where you want the frame. –  Feb 15 '16 at 23:01
  • 1
    Is this the full code? Are you intending to add methods to your `SpriteSheet` class to get individual sprites? You need something to map from cards to indexes in the sprite sheet, for one thing. – GregL Feb 15 '16 at 23:02

1 Answers1

1

That's an duplicated answer, anyway you can do it by creating one new canvas and drawing it on the main.

PS: that's not my costume code, so I'll do somethings I'd not do, as create variables, etc.

1. Create canvas element asigned as value from one variable;

var Area=document.createElement("canvas")

2. Set the frame size to this canvas;

Area.width=FrameWidth,
Area.height=FrameHeight

3. Draw the spritesheet in this canvas in the x/y (negative) where the frame you want is located;

var AContext=Area.getContext("2d");
AContext.drawImage(SpriteSheet,0-FrameX,0-FrameY);

4. Draw this canvas as image in the main canvas, but with x/y preference;

MainCanvas.drawImage(Area,PreferenceX,PreferenceY)

It's like these steps you can draw one frame from an spritesheet image. I'm not sure if it's that you want, I can't understand your question as well.