使用html5画布操作文本

时间:2012-10-25 10:11:18

标签: javascript html5 html5-canvas

你好我想画切尔西足球俱乐部的标志,我已经有了'大事' 像圆圈和内部白色空间等..和文本但我有问题...在徽标中文本就像是一个半圆形状但我找不到像这样绘制它的方法右侧文本示例的画布请参见下图,另请参阅我的代码

$(function () {

        //variables
        var canvas = document.getElementById("chelseaLogo");
        var CanvasContext = canvas.getContext("2d");
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 170;
        var radiusWhite = radius - 30;

        // outside logo
        CanvasContext.beginPath();
        CanvasContext.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        CanvasContext.fillStyle = '#0B49DB';
        CanvasContext.fill();

        //stroke
        CanvasContext.lineWidth = 2;
        CanvasContext.strokeStyle = '#FFF700';
        CanvasContext.stroke();

        //white innercircle
        CanvasContext.beginPath();
        CanvasContext.arc(centerX, centerY, radiusWhite, 0, 2 * Math.PI, false);
        CanvasContext.fillStyle = '#fff';
        CanvasContext.fill();

        //text top
        CanvasContext.font = '15pt Calibri';
        CanvasContext.fillText('Chelsea', 155, 25);

        //text bottom
        CanvasContext.font = '15pt Calibri';
        CanvasContext.fillText('Football Club', 140, 330);

});

Chelsea Logo

1 个答案:

答案 0 :(得分:3)

我修改了@Esailija发布的教程代码,使其更加准确/灵活:

function drawTextAlongArc(context, str, hei, centerX, centerY, radius, angle, above) {
    var met, wid;
    context.save();
    context.translate(centerX, centerY);
    if (!above) {
        radius = -radius;
        angle = -angle;
    }
    else{
        hei = 0;
    }
    context.rotate(-1 * angle / 2);
    context.rotate(-1 * (angle / str.length) / 2);

    for (var n = 0; n < str.length; n++) {
        var char = str[n];
        met = context.measureText(char);
        wid = met.width;
        console.log(met);

        context.rotate(angle / str.length);
        context.fillText(char, -wid / 2, -radius + hei);
        context.strokeText(char, -wid / 2, -radius + hei);
    }
    context.restore();
}
ctx.font = 'bold 40pt impact';
ctx.fillStyle = '#000';
ctx.strokeStyle = '#f00';
ctx.lineWidth = 2;
drawTextAlongArc(ctx, "CHELSEA", 40, 200, 200, 100, Math.PI*3/5, true);

ctx.font = 'bold 20pt impact';
drawTextAlongArc(ctx, "FOOTBALL CLUB", 30, 200, 200, 100, Math.PI*3/5, false);

ctx.beginPath();
ctx.arc(200,200,100,0,Math.PI*2,false);
ctx.stroke();

您可以在此处查看此示例:http://jsfiddle.net/6uQSS/1/