gpt4 book ai didi

javascript - 如何调整 Canvas 大小

转载 作者:行者123 更新时间:2023-11-30 17:11:21 25 4
gpt4 key购买 nike

我有一个默认大小为 100x100 的 Canvas 。我有 s 来决定 Canvas 应该有多大,然后只需单击一下按钮即可设置。

但它总是会调整回默认大小。

<!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();

// ...
});

关于javascript - 如何调整 Canvas 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com