繁体   English   中英

如何调整画布大小

[英]How to resize a Canvas

我有一个默认大小为100x100的画布。 我有s决定画布应该多大,然后应通过简单的按钮单击来设置。

但是,它始终会调整为默认大小。

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

单击按钮时,表单正在提交-这是默认的表单行为。 您可以防止这种情况。 更改:

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

对此:

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

    // ...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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