<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head> <body><canvas id=‘myCanvas‘ style="width: 280px; height: 280px" width="280" height="280"></canvas><script type="text/javascript"> getImg(‘候经理‘,80);function getImg(text,fsz){ var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); var img = new Image(); img.src = ‘hj.png‘; img.onload=function(){//图片加载完成,才可处理 cxt.drawImage(img,0,0,280,280,0,0,280,280); cxt.save(); cxt.font = fsz+"px Arial"; cxt.textBaseline = ‘middle‘;//更改字号后,必须重置对齐方式,否则居中麻烦。设置文本的垂直对齐方式 cxt.textAlign = ‘center‘; var tw = cxt.measureText(text).width; var ftop = c.height/2; var fleft = c.width/2; cxt.fillStyle="#ff0000"; cxt.fillRect(fleft-tw/2,ftop-fsz/2,tw,fsz);//矩形在画布居中方式 cxt.fillStyle="#ffffff"; cxt.fillText(text,fleft,ftop);//文本元素在画布居中方式 cxt.strokeStyle = ‘yellow‘; cxt.strokeText(text,fleft,ftop);//文字边框 }; } </script> </body></html>
结果
时间: 2024-10-15 11:05:35