coder
coder

Reputation: 13250

Working with HTML5 Canvas

I am working with some image manipulations and I am trying to have a basic canvas and I have a text box now If I enter any text it should change immediately on the canvas and I need that text to move on the canvas and record it's X and Y positions.So how do I do that?

Here is my code:

    <!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

    var drawLogo = function () {
        var canvas = document.getElementById('my_canvas');
        var context = canvas.getContext('2d');
        context.font = 'italic 40px sans-serif';
        context.textBaseline = 'top';
        context.fillText('Some text', 60, 0);

    };

    $(function () {
        var canvas = document.getElementById('my_canvas');
        if (canvas.getContext) {
            drawLogo();
        }
    }); 
</script>
</head> 
<body>
<canvas id="my_canvas" width="900" height="300">
Fallback content here
</canvas>
    <input id="Text1" type="text" />
</body>
</html>

Upvotes: 0

Views: 524

Answers (1)

Carlos Lima
Carlos Lima

Reputation: 36

First, everytime the text changes you'll need to re-draw the ENTIRE canvas.

Do this:

  • Add a myText, x & y inputs to your drawLogo function: drawLogo(myText, x, y) and change this line to context.fillText(myText, x, y);
  • To change text on the canvas, add a JS event handler to the textbox and call the new drawLogo function passing all 3 input parameters.
  • Keep in mind that you cannot modify what's drawn on a Canvas. You can only draw it once so all modifiers have to be done in one pass.
  • The moving part is not clear but you'll need to calculate your equations of motion in JS beforehand. When you call the new drawLogo(myText, x, y) you'll pass these values from JS.
  • Watch out for this line context.textBaseline = 'top'; as last time I checked it wasn't supported in Firefox.

Upvotes: 2

Related Questions