Build Crafty JS from source
developnpm install
grantrepository·develop·Indexed 25 days ago
https://github.com/craftyjs/craftyA modern component and event-based JavaScript game framework targeting DOM, Canvas, and WebGL. Crafty JS utilizes an Entity-Component architecture to handle rendering and DOM interaction, featuring a built-in event system, asset loading (Crafty.load), scene management (Crafty.scene), and a Model component for data isolation and change tracking. Version 0.8.0.
npm install
grantCrafty JS is a game library that uses an Entity-Component system. You can initialize the game engine using Crafty.init(width, height) and set a background color with Crafty.background(color).
Entities are created using Crafty.e("Component1, Component2, ..."), where you pass a comma-separated string of components to define the entity's capabilities (e.g., 2D, DOM, Color, Collision).
Common patterns include:
.attr({ ... }) to set properties like position (x, y) and dimensions (w, h)..bind('UpdateFrame', function() { ... }) to run logic every frame..onHit('ComponentName', function() { ... }) to handle collision events.Crafty("ComponentName") to select all entities with a specific component.When using components that support easing (such as Tween or SpriteAnimation), you can specify how the animation progresses by providing either a string representing a built-in easing function or a custom function.
Built-in easing functions include:
linear: No acceleration.smoothStep: Starts and ends with velocity 0.smootherStep: Starts and ends with velocity 0 (smoother than smoothStep).easeInQuad: Quadratic curve starting with velocity 0.easeOutQuad: Quadratic curve ending with velocity 0.easeInOutQuad: Quadratic curve starting and ending with velocity 0.Custom easing functions must accept a single parameter t (representing progress from 0 to 1) and return the calculated progress between 0 and 1.
var e = Crafty.e("2D, Tween");
// Use built-in easing functions
e.tween({x:100}, 1000, "smoothStep");
e.tween({y:100}, 1000, "easeInQuad");
// Define a custom easing function: 2t^2 - t
e.tween({w:0}, 1000, function(t){return 2*t*t - t;});The Model component allows you to isolate business logic by providing default values, tracking "dirty" (changed) values, and supporting deep events.
To use it, include this.requires('Model'); in the init function of your custom component.
Important: To ensure events are triggered correctly, always access and modify data using .get(), .set(), or .attr() rather than accessing properties directly.
Crafty.c('Person', {
name: 'Fox',
init: function() {
this.requires('Model');
}
});
// Usage example
var person = Crafty.e('Person').attr({name: 'blaine'});
person.bind('Change[name]', function() {
Crafty.log('name changed!');
});
person.attr('name', 'blainesch'); // Triggers the event2D component. To prevent an entity from being destroyed when Crafty.enterScene() or Crafty.scene(name) is called, add the Persist component to that entity.The Tween component allows you to animate numeric 2D properties over time. Supported properties include x, y, w, h, alpha, and rotation.
To use it, add the Tween component to an entity using Crafty.e("2D, Tween").
Crafty.e("2D, Tween")
.attr({alpha: 1.0, x: 0, y: 0})
.tween({alpha: 0.0, x: 100, y: 100}, 200);The tweenSpeed property controls the rate of all tweens on the entity. The default value is 1.
tweenSpeed = 0.5: Tweens take twice as long.tweenSpeed = 2.0: Tweens take half as long.The delaySpeed property controls the rate of all delays on the entity.
1 is the default.0.5 makes delays take twice as long.2.0 makes delays twice as short.The Crafty.imageWhitelist is an array of file extensions that Crafty.load recognizes as valid images. You can push new extensions to this list to support additional formats (e.g., tif).
// add tif extension to list of supported image files
Crafty.imageWhitelist.push("tif");Use Crafty.load(assets, onLoad, [onProgress], [onError]) to preload sounds, images, and sprites.
assets: A JSON-formatted object or string defining the assets. Supported top-level keys are audio, images, and sprites.onLoad: Callback function executed when all assets are successfully loaded.onProgress (optional): Callback executed for every asset loaded. Receives an object: { loaded: number, total: number, percent: number, src: string }.onError (optional): Callback executed when an asset fails to load. Receives an object with progress information and the failed asset.Crafty.support.audio is true, mp3, wav, ogg, and mp4 are supported.map of component names to coordinates.var assetsObj = {
"audio": {
"beep": ["beep.wav", "beep.mp3", "beep.ogg"],
"boop": "boop.wav"
},
"images": ["goodguy.png"],
"sprites": {
"animals.png": {
"tile": 50,
"tileh": 40,
"map": { "ladybug": [0,0], "lazycat": [0,1] }
}
}
};
Crafty.load(assetsObj,
function() {
// Success callback
Crafty.scene("main");
},
function(e) {
// Progress callback: e.percent, e.loaded, etc.
},
function(e) {
// Error callback
}
);var assetsObj = {
"audio": {
"beep": ["beep.wav", "beep.mp3", "beep.ogg"],
"boop": "boop.wav",
"slash": "slash.wav"
},
"images": ["badguy.bmp", "goodguy.png"],
"sprites": {
"animals.png": {
"tile": 50,
"tileh": 40,
"map": { "ladybug": [0,0], "lazycat": [0,1], "ferociousdog": [0,2] },
"paddingX": 5,
"paddingY": 5,
"paddingAroundBorder": 10
},
"vehicles.png": {
"tile": 150,
"tileh": 75,
"map": { "car": [0,0], "truck": [0,1] }
}
},
};
Crafty.load(assetsObj, // preload assets
function() { //when loaded
Crafty.scene("main"); //go to main scene
Crafty.audio.play("boop"); //Play the audio file
Crafty.e('2D, DOM, lazycat'); // create entity with sprite
},
function(e) { //progress
},
function(e) { //uh oh, error loading
}
);Use Crafty.enterScene(name, [data]) to immediately switch to a registered scene.
name: The name of the scene to run.data: Any type except a function. This is passed as the first parameter to the scene's init function.Behavior:
SceneDestroy with { newScene: name }.2D entities that do not have the Persist component.uninitialize function of the current scene if it exists.SceneChange with { oldScene: String, newScene: String }.initialize function of the new scene, passing data as an argument.Throws an error if data is a function or if the scene name does not exist.
// Play a scene that was defined to accept attributes
Crafty.defineScene("square", function(attributes) {
Crafty.background("#000");
Crafty.e("2D, DOM, Color")
.attr(attributes)
.color("red");
});
// Enter the scene with specific attributes
Crafty.enterScene("square", {x:10, y:10, w:20, h:20});Use Crafty.defineScene(name, init, [uninit]) to register a scene without playing it immediately.
name: The unique string ID for the scene.init: A function executed when the scene is played. It can accept one argument (data).uninit (optional): A function executed before the next scene is played, after 2D entities (without Persist) are destroyed.Throws an error if init is not a function.
Crafty.defineScene("loading", function() {
Crafty.background("#000");
Crafty.e("2D, DOM, Text")
.attr({ w: 100, h: 20, x: 150, y: 120 })
.text("Loading")
.textAlign("center")
.textColor("#FFFFFF");
});