Modifying Canvas in real time

4

How can I use the tag canvas of HTML5 and make this change in real time as I enter the data in input ? I already made form and put tag canvas on the page. I would like to know if in%% of% it is possible to change the data that I enter in JQuery and at the same time change the measurement of input :

Code :

<input type="text"name="largura"/>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var largura = document.getElementById("largura").focus().value;
    var altura = document.getElementById("altura")..focus().value;
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(5,5,largura,altura);
</script>

What would be the function in canvas that would change these variables in real time?

    
asked by anonymous 23.04.2015 / 17:49

2 answers

3

Yes, you can do this in the keyup event as in the example:

$(document).ready(function() { // Ao carregar a página
    $(this).on('keyup', 'input.canvas-settings', function(event){ // Ao soltar a tecla no input
        // Canvas.css( atributo data-prop do input, valor do input)
        $("canvas").css($(this).data('prop'), this.value);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>Largura:<inputtype="text" data-prop="width" class="canvas-settings" value="100"><br>
Altura: <input type="text" data-prop="height" class="canvas-settings" value="100"><br>
<canvas height="100" width="100" style="border:1px solid red"></canvas>

JSFiddle

    
23.04.2015 / 20:19
1

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>Largura:<inputtype="text" class="canvas-attr" id="largura" value="100"/><br/>
Altura: <input type="text" class="canvas-attr" id="altura" value="100"/><br/>
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>

JQuery

// Quando a largura ou a altura forem alteradas
$(".canvas-attr").on('change',function() {
    // Muda a largura e a altura do canvas
    var c = $("#c");
    c.attr("width",$("#largura").val());
    c.attr("height", $("#altura").val());

    // Cria variáveis com os valores de altura e largura
    var ctx = c[0].getContext("2d");
    var largura = $("#largura").val();
    var altura = $("#altura").val();

    // Cor vermelha para o preenchimento
    ctx.fillStyle = "#FF0000";
    // Colore o canvas inteiro
    ctx.fillRect(0,0,largura,altura);
});

JSfiddle

    
23.04.2015 / 19:52