效果如图所示:
完整代码如下:
//文本内容
var t = "时值小寒二日,窗外鹅毛已止,万物皆批银纱。启窗探首,双目远眺,不禁轻吟“润之”之《沁园春•雪》“北国风光,千里冰封,万里雪飘。望长城内外,惟余莽莽;大河上下,顿失滔滔。山舞银蛇,原驰蜡象,欲与天公试比高。须晴日,看红装素裹,分外妖娆。江山如此多娇,引无数英雄竞折腰……”吟罢,忽一股寒风直入肺腑,细品之,竟有雪之芳香!介此独思一物----“梅”正是陆放翁之:“幽谷那堪更北枝,年年自分着花迟。高标逸韵君知否,正是层冰积雪时”。如此画面缺此“逸韵”不免一丝遗憾。少顷一缕寒冬残阳之余晖亲扶我面,顿觉稍有情趣。此情!此景!吾闭目沉思。那时方入弱冠之年,家父常道:“我儿生逢盛世,顺风顺水。不乏大志与弘毅,勿缺聪慧与孤胆,只少逆境之坚韧,威武之屈服”,于是呼“精忠报国、黄沙碧血、金戈铁马”便伴我军旅左右。然!浩翰江水激趟过,烈日寒风势磅礴。又怎不是男儿应有之豪迈!正是人间正道沧桑,边关处,军营好男儿。卫国戍边,傲行疆场。夜伴长空皓月,望断南飞鸿雁,只待他年月明夜,凯歌相伴衣锦还";
var imgurl = "images/10.jpg";//需要显示的图像路径
var fill={
fontSize:18,//字体大小
x_text:15,//文字绘制的起始X坐标
y_text:15,//文字绘制的起始Y坐标
x_img:150,//图像绘制的起始X坐标
y_img:50,//图像绘制的起始Y坐标
w_img:150,//图像的宽度
h_img:150,//图像的高度
w:0,//画布的宽度
h:0,//画面的高度
start:function(){
var oCanvas = document.getElementById("testcanvas");
var cxt = oCanvas.getContext("2d");
this.w = oCanvas.getAttribute("width");
this.h = oCanvas.getAttribute("height");
cxt.strokeStyle="gray";
cxt.strokeRect(0,0,this.w,this.h);
var img = new Image();
img.src = imgurl;
var oThis = this;
img.onload=function(){
cxt.drawImage(img, oThis.x_img, oThis.y_img, oThis.w_img, oThis.h_img);
oThis.fillText(cxt,t);
};
},
fillText:function(cxt,text){
var oThis = this;
var len = text.length;//总字数
var curindex = 0;//当前索引
cxt.font=""+this.fontSize+"px 隶书";
var currows = 1;//当前的行数
(function(){
var nextX = oThis.x_text+oThis.fontSize*2+3;//下一个文本所占位置 x+w
if(nextX >= oThis.w){//文字要超过画布宽度时,换行
if((currows+1)*oThis.fontSize+currows*3>=oThis.h){//下一行会超出画布时
//退出
}
else {
currows = currows + 1;
oThis.x_text = 10;
oThis.y_text = oThis.y_text+oThis.fontSize+3;
cxt.fillText(text.substring(curindex,curindex+1),oThis.x_text,oThis.y_text);
curindex = curindex+1;
setTimeout(arguments.callee,1);
}
}
else {
//文字要即将与图像重合时
if(nextX>=oThis.x_img && oThis.x_text<=oThis.x_img+oThis.w_img &&
oThis.y_text>=oThis.y_img && oThis.y_text-oThis.fontSize-3
oThis.x_text = oThis.x_img+oThis.w_img+1;
}
else {
oThis.x_text = oThis.x_text+oThis.fontSize+1;
}
if((currows+1)*oThis.fontSize+currows*3>=oThis.h && oThis.x_text+oThis.fontSize*2+3>=oThis.w){//结尾
cxt.fillText("...",oThis.x_text,oThis.y_text);
}
else {
cxt.fillText(text.substring(curindex,curindex+1),oThis.x_text,oThis.y_text);
}
curindex = curindex+1;
setTimeout(arguments.callee,1);
}
})();
},
};
fill.start();
本文来源:https://www.2haoxitong.net/k/doc/1b02cf94227916888586d76c.html
文档为doc格式