gpt4 book ai didi

javascript - 来自表单值的 Canvas 宽度和高度

转载 作者:行者123 更新时间:2023-11-28 09:12:53 26 4
gpt4 key购买 nike

我有这段代码, Canvas 高度和宽度第一次从 nCol 和 nLin 值中获取值,但当 nCol 和 nLin 值发生变化时不会更新。您应该在哪里找到动态更改的代码?在 if (canvas.getContext) {} 内还是在函数 MakeCnv 内?

<html>
<body>
<canvas id="canvas">
<span style="color: red">
<b>canvas</b> not supported</span>
</canvas>
<br />
Col: <input type="text" value="3" id="nCol" />
Lin: <input type="text" value="3" id="nLin" />
Text: <input type="text" value="Text" id="texto" />
<input type="button" value="Make Canvas"
onclick="MakeCnv()" />

<script>
var canvas = document.getElementById("canvas");
var line = document.getElementById("nLin").value;
var cols = document.getElementById("nCol").value;
var cnv = null;

// resize the canvas
canvas.width = line * 32;
canvas.height = cols * 32;
canvas.style="border: blue solid 1px";

if (canvas.getContext) {
cnv = canvas.getContext("2d");
MakeCnv();
}
function MakeCnv(){
cnv.strokeStyle = "olive";
// put the text in the canvas
}
</script>
</body>
</html>

最佳答案

使用onchange 属性。将其添加到您的输入中:

<input onchange="run()">

或者在你的 JS 中使用它:

document.getElementById("nLin").onchange = run();

两者都需要定义函数run - 所有这些都必须包含变量设置:

var line,
cols;

function run() {
line = document.getElementById("nLin").value;
cols = document.getElementById("nCol").value;
}

关于javascript - 来自表单值的 Canvas 宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16091649/

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