HTML Canvas Text use form to set fill, stroke

Description

HTML Canvas Text use form to set fill, stroke

View in separate window

<!doctype html>
<html lang="en">
<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>/*from  w w w  .j  ava  2  s .  c o  m*/
<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>
<script type="text/javascript">

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();
  }

  
}
canvasApp() ;
</script> 
</body>
</html>



PreviousNext

Related