希望你一切都好!
我花了整个晚上试图弄清楚如何使用 (Math.floor(Math.random())
作为 .fillRect
的坐标> 在 HTML Canvas 元素上使用的方法。
我浏览了这个网站和网上的一些答案,但到目前为止没有任何建议有效。我目前的方法是基于 this Stack Overflow answer .
每次单击按钮时,我想在 Canvas 上的随机点绘制一个 20*20px 的矩形。除了将我从 Math
方法获得的随机数输入 .fillRect
坐标参数之外,我的一切正常。
这是我的 HTML 代码和我的 JS 代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
$("#btn").click(function() {
var rectCoord = {
"x": (Math.floor(Math.random() * 699) + 1), //Canvas is 700px wide.
"y": (Math.floor(Math.random() * 599) + 1), //Canvas is 600px high.
};
console.log(rectCoord.x, rectCoord.y)
//Test. Random X and Y points log in console correctly.
ctx.fillRect(rectCoord.x, rectCoord.y, 20, 20);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<canvas id="canvas"></canvas>
<button id="btn">Click!</button>
</div>
console.log
是我测试的地方:
1) "x"和 "y"点在每次点击时随机化,并且
2) rectCoord.x、rectCoord.y 数据点正确通过,可用于以下代码行。
随机点记录到控制台很好,每当我在 fillRect
中为坐标参数输入整数时,它就会完美地绘制一个矩形。
我只是不知道如何将随机点作为参数插入 .fillRect
中。为什么它们用作 console.log
而不是 .fillRect
的参数?
非常感谢您的任何回复,我是编码的新手,我无法解决这个问题!!非常感谢任何帮助!
最佳答案
你必须设置 Canvas 大小(也许你在样式表中有它)
然后简单地删除旧位置并更新它
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//creates a function for the random value
function rectCoord(){
return {
"x": (Math.floor(Math.random()*699)+1),
"y": (Math.floor(Math.random()*599)+1)
}
}
//defines the initial values
var x = 0,//rectCoord().x
y = 0;//rectCoord().y
//then draw
ctx.fillRect(x, y, 20, 20);
$("#btn").click(function() {
//in each click delete the previous state
ctx.clearRect(x, y, 20, 20);
//renews values
x = rectCoord().x;
y = rectCoord().y;
//renews the position of the drawing
ctx.fillRect(x, y, 20, 20);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<canvas id="canvas" width="700" height="600"></canvas>
<button id="btn">Click!</button>
</div>
关于javascript - 使用 JavaScript 数学。作为 HTML Canvas .fillRect 坐标的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269154/