简体   繁体   中英

Canvas Resizing

I have a canvas that dynamically changes size on user input ie whenever he types in input text box. It works fine if the user inputs a new size greater than the current one but if i try to shrink it the canvas size the previous value persists... how can i do this without refreshing the page? Here's the code:

<p style="line-height: 18px; font-size:18px;  font-family: times;">
<br>
<div id = "div1">
<canvas id="canvas"></canvas>
<button onclick="myFunction()">Clickme</button>
<input type= "number" id ="tx1">
<input type= "number" id ="tx2">
<script>
    function myFunction(){
        var node = document.getElementById("div1"); 
        var kid1 = document.createElement("p"); 
        var kid2 = document.createTextNode("hey"); 
        var kid3 = document.createElement("span"); 
        node.appendChild(kid1); 
        node.appendChild(kid2); 
        node.appendChild(kid3); 
    }
    window.onkeyup = function (e) {
        var code = e.keyCode ? e.keyCode : e.which;
        var t1=document.getElementById('tx1').value;
        var t2=document.getElementById('tx2').value;
        console.log(t1);
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = 'green';
        ctx.fillRect(10, 10, t1, t2);
};
</script>

Try adding a clearRect() in your code

window.onkeyup = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    var t1=document.getElementById('tx1').value;
    var t2=document.getElementById('tx2').value;
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');
    ctx.clearRect(10,10,canvas.width,canvas.height);
    ctx.fillStyle = 'green';
    ctx.fillRect(10, 10, t1, t2);
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM