简体   繁体   English

来自codepen的这段代码不能在本地主机上运行为什么

[英]this code from codepen not working on local host why

This pen from codepen is not working on localhost but everything other is working right.这支来自 codepen 的笔无法在 localhost 上运行,但其他一切都正常。 I want to know why is it not woking and how can I make it work?我想知道为什么它不工作,我怎样才能让它工作? https://codepen.io/demaine/pen/NZdXvV https://codepen.io/demaine/pen/NZdXvV

I have compiled scss to css file and included it in header.我已将 scss 编译为 css 文件并将其包含在 header 中。 I have added extra files(external scripts) that are given under JS settings.我添加了在 JS 设置下提供的额外文件(外部脚本)。

<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/poly-decomp@0.3.0/build/decomp.js"></script>
<script src="https://cdn.jsdelivr.net/npm/matter-js@0.14.2/build/matter.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
/* line 1, ../sass/manybana.scss */
*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

</style>
<script>
// Set window height and width variables
let width = window.innerWidth,
  height = window.innerHeight;

// This project uses Matter so load in the modules as necessary
var Engine = Matter.Engine,
  Render = Matter.Render,
  Runner = Matter.Runner,
  World = Matter.World,
  Mouse = Matter.Mouse,
  Body = Matter.Body,
  Bodies = Matter.Bodies,
  Vertices = Matter.Vertices,
  Composite = Matter.Composite;

// Create an engine
var engine = Engine.create();

// Create a renderer
var render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    showAngleIndicator: false,
    wireframes: false,
    background: "#f7f7f8",
    width: width,
    height: height,
    showAngleIndicator: false,
    showCollisions: false,
    showInternalEdges: false,
    showVelocity: false
  }
});

// Set the global gravity variables to be slower than normal
engine.world.gravity.y = 0.05;
engine.world.gravity.x = 0;
engine.world.gravity.scale = 0.001;

// Create runner
const runner = Runner.create();
Runner.run(runner, engine);

// Add container walls
World.add(engine.world, [
  Bodies.rectangle(width / 2, height + 150, width * 2, 60, {
    label: "ground",
    isStatic: true,
    render: {
      visible: false
    }
  }),
  Bodies.rectangle(-30, height / 2, 60, height * 2, {
    label: "left-wall",
    isStatic: true,
    render: {
      visible: false
    }
  }),
  Bodies.rectangle(width + 30, height / 2, 60, height * 2, {
    label: "right-wall",
    isStatic: true,
    render: {
      visible: false
    }
  })
]);

// Define the banana shape with a set of coordinates
const bananaSet = Vertices.fromPath(
  "0 47.6 1.6 41.2 14.4 38.6 36.8 39.2 55.2 33.6 71.2 20.2 74.8 14.2 72.6 3.2 79.8 0 77.2 4.2 78.8 13.2 84.2 16.2 85.8 29.2 75.2 48 55.2 60.4 31.6 63.8 7.4 58.2"
);

// Define how to create a new banana object
const banana = function(xPos, yPos) {
  // Add a subtle random spin
  let spin = Math.random() * 0.4 - 0.2;
  return Bodies.fromVertices(
    xPos,
    yPos,
    bananaSet,
    {
      // Add a label to check for collisions
      label: "banana",
      // Add some elasticity for bouncy bananas
      restitution: 1,
      // Zero the frictions for slippery bananas
      friction: 0,
      frictionAir: 0,
      // Add the initial rotating force
      torque: spin,
      // Add a little downward force to minimise objects sticking together
      force: { x: 0, y: 0.02 },
      // Render the banana
      render: {
        fillStyle: "#ffe417",
        strokeStyle: "#ffe417"
      }
    },
    true
  );
};

// To avoid adding too many bananas
function bananaBalancer() {
  // Check the total objects in the world minus the 3 walls (and mouse influencer but remembering that the count starts at 0)
  let total = Composite.allBodies(engine.world).length - 3;
  // Make the comparison
  if (total <= bananaCount) {
    return true;
  } else {
    return false;
  }
}

// Define the function to cancel the timeout
function cancelTimeout() {
  // Clear the interval
  clearInterval(addBananas);
  // Don't add any more bananas
  addBananas = false;
  // Exit the function
  return;
}

// Create a collision event for the bananas that hit the ground
Matter.Events.on(engine, "collisionStart", function(event) {
  let pairs = event.pairs;
  pairs.forEach(function(pair) {
    // Check if the collision is between the banana and the ground
    if (pair.bodyB.label === "banana" && pair.bodyA.label === "ground") {
      // If the addBananas timeout is running then cancel it
      if (addBananas) {
        cancelTimeout();
      }
      // Remove the banana from the world
      World.remove(engine.world, pair.bodyB.parent, [(deep = true)]);
      // Run the banana restrictor function which returns true if it is ok to add a new banana
      if (bananaBalancer()) {
        // Store the exit point for where the banana hits the ground
        let exitPoint = pair.bodyB.parent.position.x;
        // Add a new banana using the exit point
        World.add(engine.world, banana(exitPoint, -80));
      }
    }
  });
});

// Add an object to represent the mouse position on the screen
const influencer = Bodies.circle(0, 0, 5, {
  isStatic: true,
  render: {
    // Make it invisible
    visible: false
  }
});

// Add the influencer to the world
World.add(engine.world, influencer);

// Add a mouse controller
const mouse = Mouse.create(render.canvas);

// Define what happens when the mouse moves
Matter.Events.on(engine, "afterUpdate", function() {
  // Early exit condition
  if (!mouse.position.x) {
    return;
  }
  const offset1 = {
    x: 0,
    y: 0
  };
  const offset2 = {
    x: 0,
    y: 0
  };
  // Move the influencer to the mouse position
  Body.translate(influencer, {
    x: mouse.position.x - influencer.position.x - offset1.x,
    y: mouse.position.y - influencer.position.y + offset1.y
  });
});

// Set the addBananas variable as true so that it can be switched into a interval function later
let addBananas = true;

// Run the engine
Engine.run(engine);

// Run the renderer
Render.run(render);

// Count the number of bananas that are created
let bananaCount = 0;
// Define how many columns of bananas will be dropped on screen
let columns = 1;
// Give adequate spacing to avoid new bananas sticking together
const bananaSpacing = 150;
// When the document has loaded
document.addEventListener("DOMContentLoaded", function(event) {
  // Calculate the number of columns of bananas to drop
  columns = Math.floor(width / bananaSpacing);
  // Start an interval for adding bananas
  addBananas = setInterval(function() {
    for (let i = 0; i < columns - 1; i++) {
      // Increment the x axis distance to drop the banana from
      let distance = (i + 1) * bananaSpacing;
      // If the function is still running then add a new banana
      World.add(engine.world, banana(distance, -50));
      // Count the number of bananas added
      bananaCount++;
    }
  }, 400);
});

</script>
</head>
<body>
</body>
</html>

There is no error showing up.没有错误显示。 It is just a blank screen on browser.它只是浏览器上的一个空白屏幕。

I think it has to do with where you have your final script tag with all your JavaScript code is located.我认为这与您的最终脚本标签与所有 JavaScript 代码所在的位置有关。 Move all that code into the body tag and it should work.将所有代码移动到正文标记中,它应该可以工作。 For future reference I'd recommend you create a separate JavaScript file and do all your JavaScript code there, then require that file into your HTML.为了将来参考,我建议您创建一个单独的 JavaScript 文件并在那里执行所有 JavaScript 代码,然后将该文件放入您的 HTML 中。 It just makes it cleaner.它只是让它更干净。

<html>
    <head>
    <script src="https://cdn.jsdelivr.net/npm/poly-decomp@0.3.0/build/decomp.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/matter-js@0.14.2/build/matter.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <style>
        /* line 1, ../sass/manybana.scss */
        *{
        box-sizing: border-box;
        margin: 0;
        padding: 0;
        }
    </style>

    </head>
    <body>
        <script>
                // Set window height and width variables
                let width = window.innerWidth,
                  height = window.innerHeight;

                // This project uses Matter so load in the modules as necessary
                var Engine = Matter.Engine,
                  Render = Matter.Render,
                  Runner = Matter.Runner,
                  World = Matter.World,
                  Mouse = Matter.Mouse,
                  Body = Matter.Body,
                  Bodies = Matter.Bodies,
                  Vertices = Matter.Vertices,
                  Composite = Matter.Composite;

                // Create an engine
                var engine = Engine.create();

                // Create a renderer
                var render = Render.create({
                  element: document.body,
                  engine: engine,
                  options: {
                    showAngleIndicator: false,
                    wireframes: false,
                    background: "#f7f7f8",
                    width: width,
                    height: height,
                    showAngleIndicator: false,
                    showCollisions: false,
                    showInternalEdges: false,
                    showVelocity: false
                  }
                });

                // Set the global gravity variables to be slower than normal
                engine.world.gravity.y = 0.05;
                engine.world.gravity.x = 0;
                engine.world.gravity.scale = 0.001;

                // Create runner
                const runner = Runner.create();
                Runner.run(runner, engine);

                // Add container walls
                World.add(engine.world, [
                  Bodies.rectangle(width / 2, height + 150, width * 2, 60, {
                    label: "ground",
                    isStatic: true,
                    render: {
                      visible: false
                    }
                  }),
                  Bodies.rectangle(-30, height / 2, 60, height * 2, {
                    label: "left-wall",
                    isStatic: true,
                    render: {
                      visible: false
                    }
                  }),
                  Bodies.rectangle(width + 30, height / 2, 60, height * 2, {
                    label: "right-wall",
                    isStatic: true,
                    render: {
                      visible: false
                    }
                  })
                ]);

                // Define the banana shape with a set of coordinates
                const bananaSet = Vertices.fromPath(
                  "0 47.6 1.6 41.2 14.4 38.6 36.8 39.2 55.2 33.6 71.2 20.2 74.8 14.2 72.6 3.2 79.8 0 77.2 4.2 78.8 13.2 84.2 16.2 85.8 29.2 75.2 48 55.2 60.4 31.6 63.8 7.4 58.2"
                );

                // Define how to create a new banana object
                const banana = function(xPos, yPos) {
                  // Add a subtle random spin
                  let spin = Math.random() * 0.4 - 0.2;
                  return Bodies.fromVertices(
                    xPos,
                    yPos,
                    bananaSet,
                    {
                      // Add a label to check for collisions
                      label: "banana",
                      // Add some elasticity for bouncy bananas
                      restitution: 1,
                      // Zero the frictions for slippery bananas
                      friction: 0,
                      frictionAir: 0,
                      // Add the initial rotating force
                      torque: spin,
                      // Add a little downward force to minimise objects sticking together
                      force: { x: 0, y: 0.02 },
                      // Render the banana
                      render: {
                        fillStyle: "#ffe417",
                        strokeStyle: "#ffe417"
                      }
                    },
                    true
                  );
                };

                // To avoid adding too many bananas
                function bananaBalancer() {
                  // Check the total objects in the world minus the 3 walls (and mouse influencer but remembering that the count starts at 0)
                  let total = Composite.allBodies(engine.world).length - 3;
                  // Make the comparison
                  if (total <= bananaCount) {
                    return true;
                  } else {
                    return false;
                  }
                }

                // Define the function to cancel the timeout
                function cancelTimeout() {
                  // Clear the interval
                  clearInterval(addBananas);
                  // Don't add any more bananas
                  addBananas = false;
                  // Exit the function
                  return;
                }

                // Create a collision event for the bananas that hit the ground
                Matter.Events.on(engine, "collisionStart", function(event) {
                  let pairs = event.pairs;
                  pairs.forEach(function(pair) {
                    // Check if the collision is between the banana and the ground
                    if (pair.bodyB.label === "banana" && pair.bodyA.label === "ground") {
                      // If the addBananas timeout is running then cancel it
                      if (addBananas) {
                        cancelTimeout();
                      }
                      // Remove the banana from the world
                      World.remove(engine.world, pair.bodyB.parent, [(deep = true)]);
                      // Run the banana restrictor function which returns true if it is ok to add a new banana
                      if (bananaBalancer()) {
                        // Store the exit point for where the banana hits the ground
                        let exitPoint = pair.bodyB.parent.position.x;
                        // Add a new banana using the exit point
                        World.add(engine.world, banana(exitPoint, -80));
                      }
                    }
                  });
                });

                // Add an object to represent the mouse position on the screen
                const influencer = Bodies.circle(0, 0, 5, {
                  isStatic: true,
                  render: {
                    // Make it invisible
                    visible: false
                  }
                });

                // Add the influencer to the world
                World.add(engine.world, influencer);

                // Add a mouse controller
                const mouse = Mouse.create(render.canvas);

                // Define what happens when the mouse moves
                Matter.Events.on(engine, "afterUpdate", function() {
                  // Early exit condition
                  if (!mouse.position.x) {
                    return;
                  }
                  const offset1 = {
                    x: 0,
                    y: 0
                  };
                  const offset2 = {
                    x: 0,
                    y: 0
                  };
                  // Move the influencer to the mouse position
                  Body.translate(influencer, {
                    x: mouse.position.x - influencer.position.x - offset1.x,
                    y: mouse.position.y - influencer.position.y + offset1.y
                  });
                });

                // Set the addBananas variable as true so that it can be switched into a interval function later
                let addBananas = true;

                // Run the engine
                Engine.run(engine);

                // Run the renderer
                Render.run(render);

                // Count the number of bananas that are created
                let bananaCount = 0;
                // Define how many columns of bananas will be dropped on screen
                let columns = 1;
                // Give adequate spacing to avoid new bananas sticking together
                const bananaSpacing = 150;
                // When the document has loaded
                document.addEventListener("DOMContentLoaded", function(event) {
                  // Calculate the number of columns of bananas to drop
                  columns = Math.floor(width / bananaSpacing);
                  // Start an interval for adding bananas
                  addBananas = setInterval(function() {
                    for (let i = 0; i < columns - 1; i++) {
                      // Increment the x axis distance to drop the banana from
                      let distance = (i + 1) * bananaSpacing;
                      // If the function is still running then add a new banana
                      World.add(engine.world, banana(distance, -50));
                      // Count the number of bananas added
                      bananaCount++;
                    }
                  }, 400);
                });

            </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM