使用html5 canvas

时间:2015-07-20 15:19:09

标签: javascript html5 canvas

我正在使用带有Javascript的html5画布来获取用户的输入并将其打印在衬衫上,但是我在打破线条方面遇到了麻烦。如您所知,用户输入必须打印在T恤上,而且我无法在多行中打破用户的输入。我可以让用户输入转到第二行,然后包装文本,第一行变成空字符串。这是我的代码:

<html>
<head>
</head>

<title>Test</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<body>
<div id="canvasWrapper" style="position:relative">
    <canvas id="myCanvas" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
    <canvas id="textCanvas" width="100" height="50" style="position: absolute; left: 135px; top: 190px; z-index: 1;"></canvas>
</div> 

<div style="clear: both"></div><br>
<input id="textToPrint" type="text" style="position: absolute"/>

 <script type="text/javascript">

 function loadCanvas(dataURL) {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    // load image from data url
    var imageObj = new Image();
    imageObj.onload = function() {
        context.drawImage(this, 0, 0);
        context.textAlign = 'center';
        context.fillStyle = 'white';
    };

    imageObj.src = dataURL;
}
 // http: //www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
 function wrapText(context, text, x, y, maxWidth, lineHeight) {
    var cars = text.split("\n");

    for (var ii = 0; ii < cars.length; ii++) {

        var line = "";
        var words = cars[ii].split(" ");

        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);
        y += lineHeight;
    }
 }

 function DrawText() {

     var canvas = document.getElementById("textCanvas");
     var context = canvas.getContext("2d");

     context.clearRect(0, 0, 500, 600);

     var maxWidth = 400;
     var lineHeight = 60;
     var x = 20; // (canvas.width - maxWidth) / 2;
     var y = 58;


     var text = document.getElementById("textToPrint").value.toUpperCase();                

    // context.fillStyle = "rgba(255, 0, 0, 1)";
     context.clearRect(0, 0, canvas.width, canvas.height);

     context.font = "51px 'LeagueGothicRegular'";
     context.fillStyle = "#333";

     wrapText(context, text, x, y, maxWidth, lineHeight);
 }

 $(document).ready(function () {
    loadCanvas('myimage.img');

    var textCanvas = document.getElementById('textCanvas');
    var textCanvasContext = textCanvas.getContext('2d');
     $("#textToPrint").keyup(function () {
         DrawText();
     });

 });

</script>
</body>
</html>

0 个答案:

没有答案