Friday, 23 December 2011

Drag and drop shapes in EaselJS

I have been playing around with the EaselJS library recently. The EaselJS is a JavaScript library for the HTML5 canvas element that is similar to the Flash display list. The syntax is similar to Actionscript 3 which makes learning EaselJS easier. I have created a simple example with three drag and droppable shapes and some text using Graphics and Text classes.

<!DOCTYPE html>
<html>
<head>
<title>Drag and drop the shapes</title>

<script src="easel.js"></script> 
<script>

var stageWidth = 640;
var stageHeight = 480;
var stage;
var update = true;
var shape1, shape2, shape3; 

function init(){
 
 //new stage
 stage = new Stage(document.getElementById("canvas"));
 stage.enableMouseOver();
 
 //text
 var text = new Text("Drag and drop the shapes", "30px Arial", "#000000");
 text.x = stageWidth/2 - text.getMeasuredWidth()/2;
 text.y = 80;
 stage.addChild(text);
 
 //circle
 shape1 = new Shape();
 shape1.graphics.beginFill(Graphics.getRGB(0,255,0));
 shape1.graphics.drawCircle(0,0,40);
 shape1.x = stageWidth/2;
 shape1.y = stageHeight/2;
 shape1.onPress = pressHandler;
 stage.addChild(shape1);

 //rectangle 
 shape2 = new Shape();
 shape2.graphics.beginFill(Graphics.getRGB(255,0,0));
 shape2.graphics.rect(0,0,100,60);
 shape2.regX = 50;
 shape2.regY = 30;
 shape2.x = stageWidth/2 - 150;
 shape2.y = stageHeight/2;
 shape2.onPress = pressHandler;
 stage.addChild(shape2);

 //poly star
 shape3 = new Shape();
 shape3.graphics.beginFill(Graphics.getRGB(0,0,255));
 shape3.graphics.drawPolyStar(0, 0, 50, 5, 0.6, -90);
 shape3.x = stageWidth/2 + 150;
 shape3.y = stageHeight/2;
 shape3.onPress = pressHandler;
 stage.addChild(shape3);
 
 //draw to the canvas
 stage.update(); 
 Ticker.addListener(window);
}

function pressHandler(e){
 e.onMouseMove = function(ev){
  e.target.x = ev.stageX;
  e.target.y = ev.stageY;
  update = true;
 }
}

function tick(){ 
 if(update){
  update = false;
  stage.update(); 
 }
}

</script>
  
</head>
  
<body onload="init()">  
 <canvas id="canvas" width="640" height="480"></canvas> 
</body>
</html> 

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP