javascriptjqueryhtml5-canvasjcanvas

Output form input value in jCanvas


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)
)

Solution

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

    In summary we:

    $(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>