Output form input value in jCanvas

109 Views Asked by At

What would be some valid code for outputting the value of a text input to a jCanvas? For example:

Name [John Doe]

John Doe would then be outputted onto a jCanvas.

I think I have an idea about what would work, but I am not sure how to make it into valid jQuery code. Pseudocode below:

var input = #input.val

canvas.drawText(

    input

    (dimensions go here)
)
1

There are 1 best solutions below

0
almcd On BEST ANSWER

The code below achieves the output that you're looking for.

In summary we:

  • Listen for the keyup event on the #name input
  • Store the value of the input to the inputString variable whenever this occurs
  • Call the clearCanvas method of jCanvas to remove any existing text on the canvas
  • Finally use the drawText method of jCanvas to print the text to the canvas

$(document).ready(function() {
       
  var inputString;

  $('#name').on('keyup', function () {
    inputString = $(this).val();

    $('canvas').clearCanvas();

    $('canvas').drawText({
      fillStyle: '#000',
      x: 50, y: 50,
      fontSize: 30,
      align: 'left',
      respectAlign: true,
      fontFamily: 'Verdana, sans-serif',
      text: inputString
    });
  });
});
<form>
  <label for="name">Name: </label>
  <input type="text" id="name" maxlength="25" />
</form>

<canvas width="600" height="300"></canvas>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jcanvas/16.7.3/jcanvas.js"></script>