基礎使用:
canvas + stage
-
繪制幾何圖形
HTML部分
<canvas id="myCanvas" width="300" height="200">
easeljs簡單使用
</canvas>
<!-- 推薦開源CDN來選取需引用的外部JS //-->
<script src="http://cdn.gbtags.com/EaselJS/0.7.1/easeljs.min.js"></script>
JS部分
window.onload=function(){
//獲取stage
var canvas = document.getElementById("myCanvas");
var stage = new createjs.Stage(canvas);
function circle(){
//生成圓形
var circle = new createjs.Shape();
circle.graphics.setStrokeStyle(2).beginStroke("rgba(0,0,0,.5)").beginFill("orange").drawCircle(0, 0, 50);
circle.x = 55;
circle.y = 100;
//將生成圖形添加到stage中荤傲,并且調(diào)用update方法更新
stage.addChild(circle);
stage.update();
}
function rect(){
//生成矩形
var rect = new createjs.Shape();
rect.graphics.beginFill("orange").drawRect(10, 10, 100, 100);
rect.x = 120;
rect.y = 40;
//將生成圖形添加到stage中沦疾,并且調(diào)用update方法更新
stage.addChild(rect);
stage.update();
}
function polystar(){
//生成多角形
var polystar = new createjs.Shape();
polystar.graphics.setStrokeStyle(5).beginStroke("orange").drawPolyStar(290,100,5,10,10,110);
stage.addChild(polystar);
stage.update();
}
circle();
rect();
polystar();
}
上方代碼中挪钓,多次用到:
stage.update();
可以通過添加一個Ticker類幫助避免多次調(diào)用update方法,添加以下代碼轩勘,刪除stage.update()即可;
createjs.Ticker.addEventListener("tick", handleTicker);
function handleTicker(){
stage.update();
}
-
圖形屬性修改及事件綁定
function circle(){
//生成圓形
var circle = new createjs.Shape();
circle.graphics.beginFill("orange").drawCircle(0, 0, 50);
//以下方式可以方便的修改圖形相關的屬性
//修改圖形坐標
circle.x = Math.floor(Math.random() * 200);
circle.y = Math.floor(Math.random() * 350);
//修改圖形縮放
circle.scaleX = Math.floor(Math.random() * 2)+1;
circle.scaleY = Math.floor(Math.random() * 2)+1;
//修改alpha和旋轉(zhuǎn)
circle.alpha = Math.random() * 1;
circle.rotation = Math.floor(Math.random() * 60);
//設置圖形相關的鼠標事件
circle.on("click",handleClick,null,false);
circle.on("mouseout",handleMouseOut,null,false);
//將生成圖形添加到stage中隘世,并且調(diào)用update方法更新
stage.addChild(circle);
stage.update();
}
function handleClick(e){
alert("已經(jīng)點擊了圓形");
}
function handleMouseOut(e){
console.log("鼠標移出了圓形");
}
-
生成文字
//繪制10個隨機屬性的文字
function drawText(){
for(var i=0;i<10;i++){
var theText = new createjs.Text("極客標簽","normal 32px microsoft yahei","#222222");
theText.x = Math.floor(Math.random() * 350);
theText.y = Math.floor(Math.random() * 400);
theText.rotation = Math.floor(Math.random() * 360);
theText.alpha = Math.random() * 1;
theText.color = "#"+Math.floor(Math.random()*16777215).toString(16);
stage.addChild(theText);
stage.update();
}
}