Kontra​.sprite(​properties)

properties {object}
Properties of the sprite.
properties.x {number}
Optional. Sprites x coordinate. Defaults to 0.
properties.y {number}
Optional. Sprites y coordinate. Defaults to 0.
properties.dx {number}
Optional. Sprites x velocity. Defaults to 0.
properties.dy {number}
Optional. Sprites y velocity. Defaults to 0.
properties.ddx {number}
Optional. Sprites x acceleration. Defaults to 0.
properties.ddy {number}
Optional. Sprites y acceleration. Defaults to 0.
properties.ttl {number}
Optional. How many frames the sprite should be alive. Used by kontra.pool. Defaults to 0.
properties.rotation {number}
Optional. Sprites rotation around the origin in radians. Defaults to 0.
properties.anchor {object}
Optional. Sprites x and y origin. Defaults to {x:0, y:0}.
properties.context {CanvasRenderingContext2D}
Optional. The context the sprite should draw to. Defaults kontra.context.
properties.image {HTMLImageElement | HTMLCanvasElement}
Optional. Use an image to draw the sprite.
properties.animations {object}
Optional. An object of kontra.animations from a kontra.spritesheet to animate the sprite.
properties.color {string}
Optional. Fill color for the sprite if no image or animation is provided.
properties.width {number}
Optional. Width of the sprite if no image or animation is provided.
properties.height {number}
Optional. Height of the sprite if no image or animation is provided.
properties.update {function}
Optional. Function called every frame to update the sprite.
properties.render {function}
Optional. Function called every frame to render the sprite.
properties.* {*}
Optional. Any additional properties you need added to the sprite. For example, if you pass kontra.sprite({type: 'player'}) then the sprite will also have a property of the same name and value. You can pass as many additional properties as you want.

A versatile way to update and draw your game objects. It can handle simple rectangles, images, and sprite sheet animations. It can be used for your main player object as well as tiny particles in a particle engine.

let sprite = kontra.sprite({x: 300, y: 100, type: 'player'});

console.log(sprite.type);  //=> 'player'

Table of Contents

Rectangle Sprite

In its most basic form, a sprite is a rectangle with a fill color. To create a rectangle sprite, pass the properties width, height, and color. A rectangle sprite is great for initial prototyping and particles.

let sprite = kontra.sprite({ x: 290, y: 80, // required for a rectangle sprite width: 20, height: 40, color: 'red' }); sprite.render();

Image Sprite

A sprite can use an image instead of drawing a rectangle. To create an image sprite, pass the image property. The size of the sprite will automatically be set as the width and height of the image.

let image = new Image(); image.src = '../imgs/character.png'; let sprite = kontra.sprite({ x: 267, y: 54, // required for an image sprite image: image }); image.onload = function() { sprite.render(); };

Animation Sprite

A sprite can use a spritesheet animation as well. To create an animation sprite, use the animations property. The size of the sprite will automatically be set as the width and height of a frame of the spritesheet.

A sprite can have multiple named animations. The easiest way to create animations is to use kontra.spriteSheet. All animations will automatically be cloned so no two sprites update the same animation.

let image = new Image(); image.src = '../imgs/character_walk_sheet.png'; image.onload = function() { // use kontra.spriteSheet to create animations from an image let spriteSheet = kontra.spriteSheet({ image: image, frameWidth: 72, frameHeight: 97, animations: { // create a named animation: walk walk: { frames: '0..9', // frames 0 through 9 frameRate: 30 } } }); let sprite = kontra.sprite({ x: 267, y: 54, /* exclude:start */ context: context, /* exclude:end */ // required for an animation sprite animations: spriteSheet.animations }); // use kontra.gameLoop to play the animation let loop = kontra.gameLoop({ /* exclude:start */ clearCanvas: false, /* exclude:end */ update: function(dt) { sprite.update(); }, render: function() { /* exclude:start */ context.clearRect(0, 0, canvas.width, canvas.height); /* exclude:end */ sprite.render(); } }); loop.start(); };

Custom Properties

If you need to draw a different shape, such as a circle, you can pass in custom properties and a render function to handle drawing the sprite.

let sprite = kontra.sprite({ x: 300, y: 100, color: 'red', // custom properties radius: 20, render: function() { this.context.fillStyle = this.color; this.context.beginPath(); this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); this.context.fill(); } }); sprite.render();

Extending Functionality

Sprites are very flexible and easy to extend. If you need to modify or add functionality to the sprite, you can modify or add to kontra.sprite.prototype.

/* exclude:start */ let render = kontra.sprite.prototype.render; /* exclude:end */ // make all sprites a triangle kontra.sprite.prototype.render = function() { this.context.fillStyle = this.color; let halfHeight = this.height / 2; let halfWidth = this.width / 2; this.context.translate(this.x, this.y + halfHeight); this.context.lineTo(halfWidth, halfHeight); this.context.lineTo(0, -this.height); this.context.lineTo(-halfWidth, halfHeight); this.context.fill(); } let sprite = kontra.sprite({ x: 300, y: 100, color: 'red', width: 20, height: 20 }); sprite.render(); /* exclude:start */ kontra.sprite.prototype.render = render; /* exclude:end */

kontra.sprite​.acceleration

{kontra.vector}

X and Y values of the sprites acceleration vector.

kontra.sprite​.advance(dt)

dt {number}
Optional. Time since last update.

Move the sprite by it's acceleration and velocity. If the sprite is an animation sprite, it also advances the animation every frame.

If you override the sprites update() function with your own update function, you can call this function to move the sprite using the sprites normal update function.

let sprite = kontra.sprite({
  x: 100,
  y: 200,
  width: 20,
  height: 40,
  dx: 5,
  dy: 2,
  update: function() {
    // move the sprite normally
    sprite.advance();

    // change the velocity at the edges of the canvas
    if (this.x < 0 || this.x - this.width > kontra.canvas.width) {
      this.dx = -this.dx;
    }
    if (this.y < 0 || this.y - this.height > kontra.canvas.height) {
      this.dy = -this.dy;
    }
  }
});

kontra.sprite​.anchor

{object}

The x and y origin of the sprite. {x:0, y:0} is the top left corner of the sprite, {x:1, y:1} is the bottom right corner

let sprite = kontra.sprite({ x: 150, y: 100, color: 'red', width: 50, height: 50, render: function() { this.draw(); // draw origin this.context.fillStyle = 'yellow'; this.context.beginPath(); this.context.arc(this.x, this.y, 3, 0, 2*Math.PI); this.context.fill(); } }); sprite.render(); sprite.anchor = {x: 0.5, y: 0.5}; sprite.x = 300; sprite.render(); sprite.anchor = {x: 1, y: 1}; sprite.x = 450; sprite.render();

kontra.sprite​.animations

{object}

An object of kontra.animations from a kontra.spritesheet to animate the sprite. Each animation is named so that it can can be used by name for the sprites playAnimation() function.

let spriteSheet = kontra.spriteSheet({
  /* ... */,
  animations: {
    idle: {
      frames: 1,
      loop: false,
    },
    walk: {
      frames: [1,2,3]
    }
  }
});

let sprite = kontra.sprite({
  x: 100,
  y: 200,
  animations: spriteSheet.animations
});

sprite.playAnimation('idle');

kontra.sprite​.collidesWith(object)

object {object}
The object to check for collision against.

Check if the sprite collide with the object. Uses a simple Axis-Aligned Bounding Box (AABB) collision check. Takes into account the sprites anchor.

NOTE: Does not take into account sprite rotation. If you need collision detection between rotated sprites you will need to implement your own CollidesWith() function. I suggest looking at the Separate Axis Theorem.

let sprite = kontra.sprite({
  x: 100,
  y: 200,
  width: 20,
  height: 40
});

let sprite2 = kontra.sprite({
  x: 150,
  y: 200,
  width: 20,
  height: 20
});

sprite.collidesWith(sprite2);  //=> false

sprite2.x = 115;

sprite.collidesWith(sprite2);  //=> true

If you need a different type of collision check, you can override this function by passing in a property of the same name to kontra.sprite().

// circle collision
function collidesWith(object) {
  let dx = this.x - object.x;
  let dy = this.y - object.y;
  let distance = Math.sqrt(dx * dx + dy * dy);

  return distance < this.radius + object.radius;
}

let sprite = kontra.sprite({
  x: 100,
  y: 200,
  radius: 25,
  collidesWith: collidesWith
});

let sprite2 = kontra.sprite({
  x: 150,
  y: 200,
  radius: 30,
  collidesWith: collidesWith
});

sprite.collidesWith(sprite2);  //=> true

kontra.sprite​.color

{string}

The color of the sprite if it was passed into kontra.sprite().

kontra.sprite​.context

{CanvasRenderingContext2D}

The context the sprite will draw to.

kontra.sprite​.ddx

{number}

The X value of the sprites acceleration.

kontra.sprite​.ddy

{number}

The Y value of the sprites acceleration.

kontra.sprite​.draw()

Draw the sprite on its context at the its X and Y position. This function changes based on the type of the sprite. For a rectangle sprite, it uses context.fillRect(), for an image sprite it uses context.drawImage(), and for an animation sprite it uses kontra.spriteSheet.render().

If you override the sprites render() function with your own render function, you can call this function to draw the sprite using the sprites normal drawing function.

let sprite = kontra.sprite({ x: 290, y: 80, color: 'red', width: 20, height: 40, render: function() { // draw the rectangle sprite normally this.draw(); // outline the sprite this.context.strokeStyle = 'yellow'; this.context.lineWidth = 2; this.context.strokeRect(this.x, this.y, this.width, this.height); } }); sprite.render();

kontra.sprite​.dx

{number}

The X value of the sprites velocity.

kontra.sprite​.dy

{number}

The Y value of the sprites velocity.

kontra.sprite​.height

{number}

The height of the sprite. If the sprite is a rectangle sprite, it uses the value passed into kontra.sprite(), for an image sprite it is the height of the image, and for an animation sprite it is the height of a single frame of the animation.

kontra.sprite​.image

{HTMLImageElement | HTMLCanvasElement}

The image the sprite will use when drawn if passed into kontra.sprite().

kontra.sprite​.init(properties)

properties {object}
Properties of the sprite.

Use this function to reinitialize a sprite. It takes the same properties object as kontra.sprite(). Useful it you want to repurpose a sprite.

kontra.sprite​.isAlive()

Returns true if the sprites ttl is greater than 0. Primarily used by kontra.pool to know when to recycle an object.

kontra.sprite​.playAnimation(name)

name {string}
Name of the animation to play.

Set the currently playing animation of an animation sprite.

let spriteSheet = kontra.spriteSheet({
  /* ... */,
  animations: {
    idle: {
      frames: 1
    },
    walk: {
      frames: [1,2,3]
    }
  }
});

let sprite = kontra.sprite({
  x: 100,
  y: 200,
  animations: spriteSheet.animations
});

sprite.playAnimation('idle');

kontra.sprite​.position

{kontra.vector}

X and Y values of the sprites position vector.

kontra.sprite​.rotation

{number}

The rotation of the sprite around the origin in radians.

kontra.sprite​.render()

Render the sprite to its context. Calls the sprites draw() function.

kontra.sprite​.ttl

{number}

How may frames the sprite should be alive. Primarily used by kontra.pool to know when to recycle an object.

kontra.sprite​.update(dt)

dt {number}
Optional. Time since last update.

Update the sprites position based on its velocity and acceleration. Calls the sprites advance() function.

kontra.sprite​.velocity

{kontra.vector}

X and Y values of the sprites velocity vector.

kontra.sprite​.width

{number}

The width of the sprite. If the sprite is a rectangle sprite, it uses the value passed into kontra.sprite(), for an image sprite it is the width of the image, and for an animation sprite it is the width of a single frame of the animation.

kontra.sprite​.x

{number}

The X value of the sprites position.

kontra.sprite​.y

{number}

The Y value of the sprites position.