2017-06-05 92 views
0

我需要一点帮助。将ID添加到画布内的每个渲染元素

如何在画布内的每个渲染元素内添加文本?

这里提琴代表了我的想法:


 

 
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 = [ 
 
\t 
 
    \t [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);
#myCanvas { 
 
    border: 1px solid red; 
 
}
<canvas id="myCanvas" width="480" height="320"></canvas> 
 

 

 
<div class="play-btn-hld"> 
 
    <button class="play">Graj</button> 
 
</div>

我可以以某种方式添加的每个元素内的文字?理想的文本应该是data [i] [0]数字。可能吗 ?我无法把头围住它。

或者我应该使用经典的HTML和CSS来创建类似的效果?

干杯

+0

请解决您的片段,摆脱错误的。你想让每个球都有写在其上的数字? – Oen44

+0

我想解决这个问题,并且是每个球都写上数字。 –

+0

@ Oen44错误已修复,我的错误 –

回答

0

需要设置文本的xy位置是相同圆圈的位置。 加上测量文本,以便它很好地对齐。

在这里你去:

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); 
} 
+0

您不需要'ctx.closePath'它用于创建从路径上的最后一个点到上一个'ctx.moveTo'或第一个点在'ctx.beginPath()之后的一条线,它不是相反的'beginPath'和行为像'lineTo'也可以使用ctx.textAlign =“center”;而不是电脑的中心说明书 – Blindman67