【问题标题】:HTML5 Canvas : Spawn randomly positioned objects outside of the canvasHTML5 Canvas:在画布外随机生成对象
【发布时间】:2016-01-16 20:21:27
【问题描述】:

我想学习的是如何在画布之外从各个方向生成对象......即左、右、上、下。

For (i = 0; i < 10; i++) {
    ctx.beginPath();
    ctx.arc(Math.random()*Window.outerWidth, Math.random()*Window.outerHeight 30, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'black';
    ctx.fill();
    ctx.closePath();
}

所以基本上想象对象从画布屏幕的顶部、左侧、右侧和底部边缘的一些随机位置出现。甚至可能是角落。所以关键是我在理解其工作原理背后的逻辑时遇到了一些问题。我如何实现这样的目标?

请记住,我不只是在寻找答案,而是一种学习资源。如果您回答,那么请考虑教学而不是“分数”。

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    这个Math.random() * Window.outerWidth是快写的:

    var min = 0, max = Window.outerWidth;
    Math.random() * (max - min + 1) + min;
    

    要理解它,看看这个函数:

    function getRandom(min, max) { //You get number between [min, max]
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    

    如果你想在画布内添加圆圈,你需要设置:

    var min = 0,
        max = Window.outerWidth;
    

    您的代码删除 min 变量。你得到:

    Math.random() * (max - 0) + 0; // replace min by 0
    Math.random() * max // remove 0
    Math.random() * Window.outerWidth // max = Window.outerWidth
    

    你会得到:Math.random() * Window.outerWidth

    链接:

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 1970-01-01
      • 2018-06-30
      • 2012-12-28
      • 2013-06-03
      • 2012-12-31
      • 2018-07-24
      • 2012-01-02
      相关资源
      最近更新 更多