简体   繁体   中英

How to resize a Canvas

I have a canvas with the default size 100x100. I have s for deciding how big the canvas schould be, and this should then be set with a simple button click.

But It always resizes back to the default size.

<!DOCTYPE html>
<html>
<head lang="en">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="startForm">
    <label>Höhe:</label>
    <input value="500" size="4" id="height">
    <label>Breite:</label>
    <input value="500" size="4" id="width">
    <label>Seitenlänge:</label>
    <input value="50" size="4" id="length">
    <button id="ok">Start</button>
    <p/>
</form>
<canvas id="myCanvas" width="100" height="100"
    style="border:1px solid #000000;">
</canvas>
<script>
$("button").button();
$('#ok').on('click',function(){
    var w = $('#width').val();
    var h = $('#height').val();
    var l = $('#length').val();
    init(w,h,l);
});
var length;
var x,y;
function init(w,h,l){
    length = l;
    var c = document.getElementById("myCanvas");
    c.height=h;
    c.width=w;
    drawCircle();
    $('#myCanvas').on('click', function(e){
        var clickX = e.clientX;
        var clickY = e.clientY;

        if(clickX>=x && clickY>=y && clickX<=x+length && clickY<=y+length){
            drawCircle();
        }

    });
}
function drawCircle(){

    var c = document.getElementById("myCanvas");

    x = Math.round((Math.random() * (c.width-length)));
    y = Math.round((Math.random() * (c.height-length)));
    var ctx = c.getContext("2d");
    ctx.clearRect(0,0, c.width, c.height);
    ctx.beginPath();
    ctx.rect(x,y,length,length);

    var col = Math.random()*6;
    if(col<=1) {
        ctx.fillStyle = 'red';
    }else if(col<=2){
        ctx.fillStyle = 'green';
    }else if(col <=3){
        ctx.fillStyle = 'blue';
    }else if(col <=4){
        ctx.fillStyle = 'yellow';
    }else if(col <=5){
        ctx.fillStyle = 'orange';
    }else if(col <=6){
        ctx.fillStyle = 'black';
    }

    ctx.fill();
    ctx.stroke();
}
</script>   
</body>
</html> 

When you click the button, the form is submitting - which is default form behavior. You can prevent this. Change:

$('#ok').on('click',function (){
    // ...
});

to this:

$('#ok').on('click',function (event){
    event.preventDefault();

    // ...
});

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