js+html绘制文字居中,CreateJs系列教程之 EaselJs_2_绘制文字(Text)

核心Js代码:

var canvas,

stage,

w = window.innerWidth,

h = window.innerHeight;

function init() {

//设置canvas属性

canvas = document.getElementById('game');

canvas.width = w;

canvas.height = h;

//创建舞台

stage = new createjs.Stage(canvas);

//绘制居中文字

var text1 = new createjs.Text("Hello World", "20px Arial", "#ff4400"),

bounds = text1.getBounds();

text1.x = stage.canvas.width - bounds.width >> 1;

text1.y = stage.canvas.height - bounds.height >> 1;

//绘制左边文字

var text2 = new createjs.Text("Hello World", "20px Arial", "#ff4400");

//绘制右边文字

var text3 = new createjs.Text("Hello World", "40px Arial", "#ff4400"),

bounds = text3.getBounds();

text3.x = w - bounds.width;

//下居中文字

var text4 = new createjs.Text("Hello World", "20px Arial", "#ff7700"),

bounds = text4.getBounds();

text4.x = stage.canvas.width - bounds.width >> 1;

text4.y = stage.canvas.height - bounds.height;

stage.addChild(text1);

stage.addChild(text2);

stage.addChild(text3);

stage.addChild(text4);

stage.update();

}

说明讲解:

1:绘制舞台类

createjs.Stage(canvas HTML)

2:绘制文字类

createjs.Text('text', 'font-size font-family', '#color')

3:获得文字边界属性

Text.getBounds();

其中包含的属性有: width,height等;

4:添加到舞台

stage.addChild(displayObject);

5:更新画板显示出来

stage.update();

6:追加居中的另一种方式

//居中文字另一种方法

var text5 = new createjs.Text("Hello World", "20px Arial", "#ff7700");

text5.textAlign = 'center';//以自身的位置居中,自己的宽度,0 width/2,width

text5.x = stage.canvas.width / 2;

效果展示:

5e663d1e40a881db0aa75b027db5ca3a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值