首先是html代码(其实就只有一个画布,记得要把外部js引入写在body底部
<!doctype html><html> ???<head> ???????<meta http-equiv="content-type" content="text" charset="utf-8" /> ???</head> ???<body> ???????<canvas id="one" height="1000" width="1000"></canvas> ???????<script ?src="./weixin.js"></script> ???</body></html>
圆中写文字用到 文字的定位
用textBaseline定位高度在中间,
用textAlign定位宽度在中间
以下代码画了有边缘的圆及文字
var c=document.getElementById("one");var ctx=c.getContext("2d");ctx.strokeStyle="black";ctx.beginPath();ctx.fillStyle="lightgreen";ctx.arc(100,100,50,0,Math.PI*2,false);ctx.stroke();ctx.fill();ctx.beginPath();ctx.fillStyle="white";ctx.font="40px Arial";ctx.textBaseline="middle";ctx.textAlign="center";ctx.fillText("He",100,100);ctx.strokeText("He",100,100);
以下是随机运动的圆(不过这个圆和文字是没有边缘线的,因为我觉得加边缘线太丑了),令人苦笑不得的是最后它们都停留在了画布边缘..
var c = document.getElementById("one");var ctx = c.getContext("2d");var arrHe = [];var arrNe = [];var numHe = 100;var numNe = 5;//随机点 ???for (var i = 0; i < numHe; i++) { ???arrHe.push({ ???????x: rnd(c.width,50), ???????y: rnd(c.height,50), ???????speedX: rndSign() * rnd(1,0), ???????speedY: rndSign() * rnd(1,0) ???});}setInterval(function (){ctx.clearRect(0, 0, c.width, c.height);//He绘画 arrHe.forEach(function(dot) { ???var { ???????x, ???????y, ???????speedX, ???????speedY ???} = dot; ???ctx.beginPath(); ???ctx.fillStyle = "lightgreen"; ???ctx.arc(dot.x, dot.y, 50, 0, Math.PI * 2, false); ???ctx.fill(); ???ctx.beginPath(); ???ctx.fillStyle = "white"; ???ctx.font = "40px Arial"; ???ctx.textBaseline = "middle"; ???ctx.textAlign = "center"; ???ctx.fillText("He", dot.x, dot.y); ???if (dot.x < 0 || dot.x > c.width) { ???????speedX *= -1; ???} ???if (dot.y < 0 || dot.y > c.height) { ???????speedY *= -1; ???} ???dot.x += speedX; ???dot.y += speedY; ???});},16);//生成随机点位置和随机方向function rnd(m,n) { ???return Math.random() * (m-n);}function rndSign() { ???return Math.random() >0.5 ? 1:-1;}
array.forEach(function(currentValue, index, arr), thisValue)
currentValue 必须。当前元素。
index 可选。当前元素的索引值。
arr 可选。当前元素所属的数组对象。
thisValue 可选。不填时,默认为this
js带文字的圆随机运动
原文地址:https://www.cnblogs.com/fy-xjw/p/9739701.html