首页 > 代码库 > canvas

canvas

function wrapText(context, text, x, y, maxWidth, lineHeight) {
            var words = text.split(" ");
            var line = "";

            for (var n = 0; n < words.length; n++) {
                var testLine = line + words[n] + " ";
                var metrics = context.measureText(testLine);
                var testWidth = metrics.width;
                if (testWidth > maxWidth) {
                    context.fillText(line, x, y);
                    line = words[n] + " ";
                    y += lineHeight;
                } else {
                    line = testLine;
                }
            }

            context.fillText(line, x, y);
        }

        window.onload = function() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            var maxWidth = 20;
            var lineHeight = 25;
            var x = 180;
            var y = 150;
            var text = "王 小 彩";
            context.beginPath();
            context.arc(x, y, 50, Math.PI / 2, (Math.PI / 2) * 3);
            context.fillStyle = ‘yellow‘;
            context.fill();
            context.closePath();
            context.beginPath();
            context.moveTo(x / 2 + 30, y - 80);
            context.lineTo(x, y);
            context.moveTo(x / 2, y - 50);
            context.lineTo(x, y);
            context.moveTo(x / 2 - 10, y);
            context.lineTo(x, y);
            context.moveTo(x / 2, y + 50);
            context.lineTo(x, y);
            context.moveTo(x / 2 + 30, y + 80);
            context.lineTo(x, y);
            context.strokeStyle = "yellow";
            context.stroke();
            context.closePath();
            context.font = "12px Calibri";
            context.fillStyle = "#333";
            wrapText(context, text, x - 25, y - 20, maxWidth, lineHeight);

            var x2 = x + 30;
            var text2 = "王 小 彩"
            context.beginPath();
            context.arc(x2, y, 50, (Math.PI / 2) * 3, Math.PI / 2);
            context.fillStyle = ‘yellow‘;
            context.fill();
            context.closePath();
            context.beginPath();
            context.moveTo(x2 + x / 2 - 30, y - 80);
            context.lineTo(x2, y);
            context.moveTo(x2 + x / 2, y - 50);
            context.lineTo(x2, y);
            context.moveTo(x2 + x / 2, y);
            context.lineTo(x2, y);
            context.moveTo(x2 + x / 2, y + 50);
            context.lineTo(x2, y);
            context.moveTo(x2 + x / 2 - 30, y + 80);
            context.lineTo(x2, y);

            context.strokeStyle = "yellow";
            context.stroke();
            context.closePath();
            context.font = "12px Calibri";
            context.fillStyle = "#333";

            wrapText(context, text2, x2 + 15, y - 20, maxWidth, lineHeight);

        };

html:

<canvas id="canvas" width="437" height="267"></canvas>