【发布时间】:2017-09-17 21:45:23
【问题描述】:
希望你一切都好!
我整个晚上都在试图弄清楚如何使用 (Math.floor(Math.random()) 作为 HTML 画布元素上使用的 .fillRect 方法的坐标。
我在这个网站和网上寻找了一些答案,但到目前为止没有任何建议有效。我目前的做法是基于this Stack Overflow answer。
每次单击按钮时,我都想在画布上的任意点绘制一个 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 的参数?
非常感谢您的任何回复,我对编码很陌生,我无法理解这个!非常感谢任何帮助!
【问题讨论】:
-
你试过设置
ctx.fillStyle = 'black'或类似的东西吗? -
是的,这没什么区别。
fillStyle在默认情况下无论如何都是黑色的,当我为坐标参数输入数字(例如 40、500)时,代码会正常运行。这就是为什么我认为这与我尝试使用变化的变量作为坐标值有关。 @PatrickRoberts -
您应该使用
ctx.fillRect((Math.random()*ctx.canvas.width-20) | 0,(Math.random() * ctx.canvas.height -20) | 0, 20, 20);确保画布上始终出现一个20 x 20的矩形。
标签: javascript jquery html canvas