HTML5 Canvas Text文本居中實例


1.代碼:

<canvas width="700" height="300" id="canvasOne" class="canvasOne"></canvas>
<script>
    var cancasOne = document.getElementById('canvasOne');
    var ctx = cancasOne.getContext('2d');
    var text = '后會無期',
        textMetrics,
        square_width = 20,
        font_height = 128;
    //畫網線
    function drawGrid(color, stepx, stepy) {
        ctx.save();
        ctx.strokeStyle = color;
        ctx.lineWidth = 0.5;
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvasOne.width, canvasOne.height);
        //畫豎線
        for (var i = stepx + 0.5; i < canvasOne.width; i += stepx) {
            ctx.beginPath();
            ctx.moveTo(i, 0);
            ctx.lineTo(i, canvasOne.height);
            ctx.stroke();
        }
        //畫橫線
        for (var i = stepx + 0.5; i < canvasOne.height; i += stepy) {
            ctx.beginPath();
            ctx.moveTo(0, i);
            ctx.lineTo(canvasOne.width, i);
            ctx.stroke();
        }
        ctx.restore();
    }
    //畫文本
    function drawText() {
        ctx.fillStyle = 'orange';
        ctx.strokeStyle = 'cornflowerblue';
        ctx.fillText(text, canvasOne.width / 2,
            canvasOne.height / 2);
        ctx.strokeText(text, canvasOne.width / 2,
            cancasOne.height / 2);
    }
    //畫中間的小正方形
    function drawCenterSquare() {
        ctx.fillStyle = 'rgba(255,0,0,0.4)';
        ctx.strokeStyle = 'black';
        ctx.fillRect(canvasOne.width / 2 - square_width / 2,
            canvasOne.height / 2 - square_width / 2,
            square_width, square_width);
        ctx.strokeRect(canvasOne.width / 2 - square_width / 2,
            cancasOne.height / 2 - square_width / 2,
            square_width, square_width);
    }
    ctx.font = '128px Helvetica';
    ctx.textBaseline = 'middle'; //設置文本的垂直對齊方式
    ctx.textAlign = 'center';//設置文本的水平對齊方式
    textMetrics = ctx.measureText(text);
    drawGrid('lightgray', 10, 10);
    drawText();
    drawCenterSquare();
</script>

2.顯示結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM