My Blog

My WordPress Blog

My Blog

My WordPress Blog

Getting Started with StageXL

Installation:

  1. Install Dart SDK.
  2. Create a new Dart project and add the StageXL dependency to your pubspec.yaml:yamlCopy codedependencies: stagexl: ^2.0.0

Basic Setup:

dartCopy codeimport 'dart:html';
import 'package:stagexl/stagexl.dart';

void main() {
  // Create a Stage
  var canvas = CanvasElement(width: 800, height: 600);
  document.body.append(canvas);
  
  var stage = Stage(canvas);
  var renderLoop = RenderLoop();
  renderLoop.addStage(stage);
  
  // Background Color
  stage.stageColor = Color.Black;
}

2. Drawing Shapes

Creating Shapes:

void createShapes(Stage stage) {
  var rectangle = Shape()
..graphics.rect(50, 50, 200, 100)
..graphics.fillColor(Color.Red);
stage.addChild(rectangle); }

3. Loading Images

Image Loading Example:

void loadImage(Stage stage) {
  var loader = BitmapData.load('path/to/image.png');
  loader.onLoad.listen((_) {
var bitmap = Bitmap(loader.data);
bitmap.x = 100;
bitmap.y = 100;
stage.addChild(bitmap);
}); }

4. Handling Events

Mouse Click Event:

void setupMouseEvents(Stage stage) {
  stage.onMouseClick.listen((MouseEvent e) {
print('Mouse clicked at: ${e.stageX}, ${e.stageY}');
}); }

5. Animation Loop

Creating an Animation:

void animate(Stage stage) {
  var circle = Shape()
..graphics.circle(50, 50, 30)
..graphics.fillColor(Color.Blue);
stage.addChild(circle); int dx = 2; // change in x stage.onEnterFrame.listen((_) {
circle.x += dx;
if (circle.x > stage.stageWidth || circle.x < 0) {
  dx = -dx; // Reverse direction
}
}); }

6. Using Tiled Backgrounds

Tile a Background:

void createTiledBackground(Stage stage) {
  var bitmapData = BitmapData.load('path/to/tile.png');
  
  for (var i = 0; i < stage.stageWidth; i += 50) {
for (var j = 0; j &lt; stage.stageHeight; j += 50) {
  var tile = Bitmap(bitmapData.data)
    ..x = i
    ..y = j;
  stage.addChild(tile);
}
} }

7. Text and Fonts

Adding Text:

void addText(Stage stage) {
  var textField = TextField()
..text = 'Hello, StageXL!'
..defaultTextFormat = TextFormat('Arial', 24, Color.White);
stage.addChild(textField); }

8. Building a Simple Game Loop

Game Loop Example:

void gameLoop(Stage stage) {
  var player = Shape()
..graphics.rect(0, 0, 50, 50)
..graphics.fillColor(Color.Green);
stage.addChild(player); stage.onEnterFrame.listen((_) {
// Update player position, handle input, etc.
player.x += 1;
if (player.x > stage.stageWidth) {
  player.x = 0; // Reset position
}
}); }
Getting Started with StageXL

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top