【问题标题】:How to set a random speed in a canvas如何在画布中设置随机速度
【发布时间】:2018-07-06 09:18:24
【问题描述】:

我试图让球以随机速度下落,但只有当我重新加载页面/脚本时速度才会改变,我想动态获得随机速度,一个球在 5 时出现,下一个在 1.4 时, 下一个 2.6 等等...

https://codepen.io/Le-future/pen/gKNoEE

我尝试使用以下内容:

// set how fast the objects will fall
var spawnRateOfDescent = Math.random() * (5 - 0.5) + 0.5;

【问题讨论】:

    标签: performance animation canvas random


    【解决方案1】:

    每个球都应该有自己独特的速度属性。您可以按如下方式添加:

    第一次调整(第 72-73 行):

        image: images[Math.floor(Math.random()*images.length)], // add a comma here
        speed: Math.random() * 10 + 3 // add this line and tweak the numbers to taste
    

    第二次调整在您的 animate 函数中(第 107 行 [如果您添加了一行,则为第 108 行]):

        object.y += object.speed; // instead of: object.y += spawnRateOfDescent;
    

    【讨论】:

    • 你是超级巨星!谢谢:-)
    • 我还有一个问题,我想知道为什么图片有点像素化,你有什么想法吗?
    • 我刚刚尝试添加:ctx.mozImageSmoothingEnabled = true; ctx.webkitImageSmoothingEnabled = true; ctx.msImageSmoothingEnabled = true; ctx.imageSmoothingEnabled = true;在 onload 函数中,但不确定是否有帮助
    • 如果您尝试放大不是 SVG 的图像,我认为这些内容都无济于事。您的文件格式是svg.png,这听起来更像是 PNG 而不是 SVG。 SVG 是可缩放的(可放大的),但 PNG 只能按比例缩小。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-02-14
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多