javascript - Canvas fill shape with text -


i have this example in canvas. know how can add text in shapes.

i have looked code draws shapes not sure how add text. able add text doesn't move balls?

function draw()             {                 context.clearrect(0, 0, stagewidth, stageheight);                 var = balls.length;                 while(--i > -1)                 {                     context.fillstyle = balls[i].color;                     context.beginpath();                     context.arc(balls[i].x,balls[i].y,balls[i].size,0,math.pi*2,true);                     context.closepath();                     context.fill();                 }             } 

you have use ball's x , y value make sure text follow ball, , use textalign , textbaseline align text.

function draw() {     context.clearrect(0, 0, stagewidth, stageheight);     // align once all.     context.textalign = 'center'; // set text align center.     context.textbaseline = 'middle'; // set text vertical align middle.     var = balls.length;     while(--i > -1)     {         context.fillstyle = balls[i].color;         context.beginpath();         context.arc(balls[i].x,balls[i].y,balls[i].size,0,math.pi*2,true);         context.closepath();         context.fill();         // easier see text.         context.fillstyle = 'black';         // draw text `ball # i` centered @ position (x, y),         // width of text equal ball's size * 2.         context.filltext('ball #' + i, balls[i].x ,balls[i].y, balls[i].size * 2);     } } 

see altered jsfiddle, want?

p.s : when playing canvas, it's best keep html5 canvas cheat sheet handy.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -