Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วาดข้อความในวงกลมบน HTML5 Canvas (Circle Text)

วาดวงกลม แล้ววาด Text ตรงกลาง

$('#demo').on('click', '#canvas1', function(event) {
    var canvas = document.getElementById('canvas1');
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        var radius = 25;
        var x = event.pageX - $(this).offset().left;
        var y = event.pageY - $(this).offset().top;
        
        // วาดวงกลม
        ctx.beginPath();
        ctx.fillStyle = 'blue';
        ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
        ctx.fill();
        
        // วาดข้อความตรงกลาง
        ctx.font = '9pt Arial';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('amit', x, y);
    }
});

HTML

<div id="demo">
  <canvas id="canvas1" width="500" height="300"></canvas>
</div>

จุดสำคัญ: textAlign: 'center' + textBaseline: 'middle' จัดให้ Text อยู่กึ่งกลางวงกลมพอดี