【问题标题】:How to print random number of times one drawing in canvas javascript?如何在画布javascript中随机打印一次绘图?
【发布时间】:2021-03-17 20:26:14
【问题描述】:

我有一个画布,我在一个函数中绘制了一个矩形,在一个新函数中,我需要在 5 到 10 之间随机打印这个正方形。

我知道我必须使用Math.floor(Math.random() * 5) + 5,但现在我需要做的是随机打印矩形 5 或 10 次。

这是我到目前为止所得到的,但不知道如何使它工作

function rectangle() {
  ctx.beginPath();
  ctx.rect(20, 20, 150, 100);
  ctx.stroke();
}

function randomRect(){
  Math.floor(Math.random() * 5) + 5;
  rectangle()
}

【问题讨论】:

  • 你需要在let count = Math.floor(Math.random() * 5) + 5;上循环,你还需要调整起始位置

标签: javascript canvas random


【解决方案1】:

您可以使用Math.random 作为for 循环内的参数。

const ctx = document.querySelector('canvas').getContext('2d');

function rectangle(x, y) {
  ctx.beginPath();
  ctx.rect(x, y, 50, 50);
  ctx.stroke();
}

function randomRect() {
  const squareCount = Math.floor(Math.random() * 5) + 5;
  for (var i = 0; i < squareCount; i++) {
    // Stagger the x,y position so the squares aren't on top of each other
    rectangle(i * 10, i * 10);
  };
};

randomRect()
canvas {
  width: 400px;
  height: 400px;
  border: 1px dashed firebrick;
}
&lt;canvas&gt;&lt;/canvas&gt;

【讨论】:

  • 诱惑为-1,所有的矩形将被渲染在彼此之上,也许你可以将x,y坐标传递给rectangle(x, y)
  • 我知道这一点。 OP 要求提供一种多次运行函数的方法。不是如何随机放置矩形。
  • 好吧,我明白你的意思,但回答一个没有意义的问题没有意义...... :) 你必须至少提到你的解决方案的明显缺点,要么写解决方案甚至更好,请 OP 尝试您的建议,以便他们学习
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多