在画布的每个象限中确定点

  • 本文关键字: javascript html5-canvas
  • 更新时间 :
  • 英文 :


如何将画布划分为四个象限(左上、左下、右上、右下),然后在每个象限中确定随机绘制的点?

这是我不那么徒劳的尝试:

var myCanvas = document.getElementById("showCanvas");
var myContext = myCanvas.getContext("2d");
var xAxis = [];
var yAxis = [];
for (var i = 0; i < 4; i++) {
var x = Math.floor(Math.random() * 600);
var y = Math.floor(Math.random() * 350);
var r = 5;
xAxis.push(x);
yAxis.push(y);
myContext.arc(x, y, r, 0, 2 * Math.PI, true);
myContext.closePath();
myContext.fill();
}
var startingPoint = xAxis[0] + ", " + yAxis[0];
var endingPoint = xAxis[3] + ", " + yAxis[3];
var horizontalSlash = myCanvas.width / 2;
var verticalSlash = myCanvas.height / 2;
var remainder = horizontalSlash % verticalSlash;
<canvas id="showCanvas"></canvas>

结果应该显示在这些标签中:

<h3>The starting point of the line is: <label id="sumPoints">e.g. top, right</label></h3>
<h3>The end point of the line is: <label id="sumPoints">e.g. bottom, left</label></h3>

检查点坐标的建议是正确的…
下面是一个使用数学的例子。

const canvas = document.getElementById("showCanvas");
const ctx = canvas.getContext("2d");
const names = [
["top left",  "bottom left"],
["top right", "bottom right"]
]
var points = []
for (var i = 0; i < 4; i++) {
var x = Math.random() * canvas.width
var y = Math.random() * canvas.height
var quadrant = names[Math.floor(x / (canvas.width / 2))][Math.floor(y / (canvas.height / 2))]
points.push({ x, y, quadrant })
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fillText(quadrant, x-8, y-8)
ctx.closePath();
ctx.fill();
}
console.log(points[0])
canvas {
border:2px dotted gray;  
}
<canvas id="showCanvas" width=200 height=200></canvas>

相关内容

  • 没有找到相关文章

最新更新