zoukankan      html  css  js  c++  java
  • 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.显示结果:

  • 相关阅读:
    在 Java SE 6 中监视和诊断性能问题
    Codeforces Round #491 (Div. 2)部分题解
    BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(模拟 调和级数)
    BZOj1261: [SCOI2006]zh_tree(dp)
    BZOJ1569: [JSOI2008]Blue Mary的职员分配(dp 暴力)
    BZOJ4300: 绝世好题(dp)
    树上莫队算法
    SPOJ COT2
    BZOJ1086: [SCOI2005]王室联邦(贪心,分块?)
    Educational Codeforces Round 42 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/tianma3798/p/5563629.html
Copyright © 2011-2022 走看看