HTML5 Game - Draw text from text field

Description

Draw text from text field

Demo

ResultView the demo in separate window

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH3EX1: Text Arranger Version 1.0</title>
<script type="text/javascript">

window.addEventListener("load", eventWindowLoaded, false);  
function eventWindowLoaded() {/*from  w  ww  . j  a  v  a2  s.c o m*/
  canvasApp();
}

function canvasApp() {
  let message = "your text";
  let fillOrStroke ="fill";
  
  let theCanvas = document.getElementById("canvasOne");
  let context = theCanvas.getContext("2d"); 
  
  let formElement = document.getElementById("textBox");
  formElement.addEventListener("keyup", textBoxChanged, false);  
  
  formElement = document.getElementById("fillOrStroke");
  formElement.addEventListener("change", fillOrStrokeChanged, false);  
  
  drawScreen();
  
  function drawScreen() {
    //Background
    
    context.fillStyle = "#ffffaa";
    context.fillRect(0, 0, theCanvas.width, theCanvas.height);
    //Box
    context.strokeStyle = "#000000"; 
    context.strokeRect(5,  5, theCanvas.width-10, theCanvas.height-10);
    
    //Text
    
    context.font =  "50px serif" 
    
    let metrics = context.measureText(message);
    let textWidth = metrics.width;
    let xPosition = (theCanvas.width/2) - (textWidth/2);
    let yPosition = (theCanvas.height/2);
    
    switch(fillOrStroke) {
      case "fill":
        context.fillStyle    = "#FF0000";
            context.fillText  ( message,  xPosition ,yPosition);
        break;
      case "stroke":
        context.strokeStyle = "#FF0000";
        context.strokeText  ( message, xPosition,yPosition);
        break;
      case "both":
        context.fillStyle    = "#FF0000";
            context.fillText  ( message,  xPosition ,yPosition);
        context.strokeStyle = "#000000";
        context.strokeText  ( message, xPosition,yPosition);
        break;    
    }
          
  }
  
  function textBoxChanged(e) {
    let target =  e.target;
    message = target.value;
    drawScreen();
  }
  
  function fillOrStrokeChanged(e) {
    let target =  e.target;
    fillOrStroke =  target.value;
    drawScreen();
  }

  
}

</script> 
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="300">
 Your browser does not support HTML 5 Canvas. 
</canvas>

<form>
 
  Text: <input id="textBox" placeholder="your text" />
  <br> 
  
  Fill Or Stroke : 
  <select id="fillOrStroke">
  <option value="fill">fill</option>
  <option value="stroke">stroke</option>
   <option value="both">both</option>
  </select>
  <br>
 
</form>
  
</div>
</body>
</html>

Related Topic