简体   繁体   中英

Center Text Vertically Canvas

I have this little script. How can I center the text vertically? In another words, I need to bring out a variable from the function "wrapText" in order to use it to calculate the position of the text. Thanks a lot!

<canvas id="myCanvas" width="900" height="600" style="display:none;"></canvas>
<img id="canvasImg">

<script>

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();

imageObj.onload = function()
{
    context.drawImage(imageObj, 0, 0);
}  

imageObj.src = "img/imagea.jpg"; 

var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)

{
    var text = document.getElementById('area1').value;

 if(text.lenght == 0)
    {
         alert("you forgot to put something");
    }



function wrapText(context, text, x, y, maxWidth, lineHeight) {

    var convtext = text.replace(/\n/g, ' |br| ');
    var words = convtext.split(' ');
    var line = '';

     for(var n = 0; n < words.length; n++) {
      var newline = false;
    if (words[n].indexOf("|br|") > -1) newline = true;

    var metrics = maxWidth;
    var testWidth = maxWidth;
    var testLine = line + words[n] + ' ';

    if (context.measureText) {
    metrics = context.measureText(testLine);
    testWidth = metrics.width;
    }

    if ((testWidth > maxWidth && n > 0) || newline) {
    context.fillText(line, x, y);
    if (!newline) line = words[n] + ' ';
    if (newline) line = "";
    y += lineHeight;
    } else {
    line = testLine;
    }

    }

    context.fillText(line, x, y);

  }


  var maxWidth = 500;
  var lineHeight = 40;
  var x = 100;
  var y = 100;


 context.font = "30pt HelveticaNeue-Light";
 wrapText(context, text, x, y, maxWidth, lineHeight);
 context.fillStyle = "#009bdc";
 context.fillText("try", 100, 500);


  var dataURL = canvas.toDataURL();

  document.getElementById('canvasImg').src = dataURL;

    e.preventDefault();


});

</script>

Here's how:

  1. Modify wrapText to return the ending height value (so you can calculate the paragraph height).
  2. Modify wrapText to optionally not draw (==optionally, not do fillText )
  3. Run wrapText once in the no-draw mode to get the height of the wrapped paragraph.
  4. Calculate a starting y that will produce a vertically centered paragraph: var centeringY = maxHeight/2 - paragraphHeight/2
  5. Run wrapText again in the yes-draw mode using centeringY .

Example code and a Demo:

A paragraph of wrapped text that's vertically centered...

在此处输入图片说明

 var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var maxWidth = 150; var lineHeight = 20; var x = 100; var y = 100; var text='It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness.'; context.font='12px verdana'; var height=wrapTextVCentered(context,text,x,y,maxWidth,lineHeight,true); var y=(canvas.height-height)/2; wrapTextVCentered(context,text,x,y,maxWidth,lineHeight,false); context.strokeStyle='green'; context.strokeRect(x,y,maxWidth,height); function wrapTextVCentered(context,text,x,y,maxWidth,lineHeight,measureOnly){ var height=0; var convtext = text.replace(/\\n/g, ' |br| '); var words = convtext.split(' '); var line = ''; context.textBaseline='top'; for(var n = 0; n < words.length; n++){ var newline = false; if (words[n].indexOf("|br|") > -1) newline = true; var metrics = maxWidth; var testWidth = maxWidth; var testLine = line + words[n] + ' '; if (context.measureText){ metrics = context.measureText(testLine); testWidth = metrics.width; } if ((testWidth > maxWidth && n > 0) || newline){ if(!measureOnly){ context.fillText(line, x, y); } if (!newline) line = words[n] + ' '; if (newline) line = ""; y += lineHeight; height += lineHeight; } else { line = testLine; } } if(!measureOnly){ context.fillText(line, x, y); } height += lineHeight; return(height); } 
 body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; } 
 <h4>Vertically centered paragraph on canvas</h4> <canvas id="canvas" width=350 height=350></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM