我无需帮助。
如何在画布内的每个渲染元素中添加文本?
这是代表我的想法的小提琴:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x_width = canvas.width;
var y_height = canvas.height;
var dx = 2;
var dy = -2;
var ballRadius = 10;
var data = [
[1,0.506,0.648],
[2,0.253,0.433],
[5,0.339,0.445],
[7,0.396,0.569],
[8,0.271,0.583],
[9,0.307,0.187],
[10,0.431,0.213],
[12,0.71,1.045],
[13,0.2,0.259],
[14,0.272,0.259],
[15,0.477,0.379]
];
for (var i = 0; i<=data.length-1; i++) {
var x = x_width*data[i][1];
var y = y_height*data[i][2];
var id = data[i][0];
drawPlayer (id, x,y);
}
function drawPlayer(id, x, y) {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.fillText(id, 0, 0);
ctx.closePath();
}
drawPlayer();
//setInterval(draw , 100);
&#13;
#myCanvas {
border: 1px solid red;
}
&#13;
<canvas id="myCanvas" width="480" height="320"></canvas>
<div class="play-btn-hld">
<button class="play">Graj</button>
</div>
&#13;
我可以以某种方式在每个元素中添加文本吗?理想情况下,文本应该是data [i] [0]数字。可能吗 ?我无法绕过它。
或者我应该使用经典的html和css来创建类似的效果吗?
干杯
答案 0 :(得分:0)
您需要将文字的x
和y
位置设置为与圆圈的位置相同。
加上测量文本以使其很好地对齐。
你去:
function drawPlayer(id, x, y) {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
const textWidth = ctx.measureText(id);
const textHeight = 12 * 0.5;
ctx.font = "12px Arial"
ctx.fillStyle = "#fff";
ctx.fillText(id, x-textWidth.width/2, y+textHeight/2);
}