簡體   English   中英

來自codepen的這段代碼不能在本地主機上運行為什么

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

這支來自 codepen 的筆無法在 localhost 上運行,但其他一切都正常。 我想知道為什么它不工作,我怎樣才能讓它工作? https://codepen.io/demaine/pen/NZdXvV

我已將 scss 編譯為 css 文件並將其包含在 header 中。 我添加了在 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>

沒有錯誤顯示。 它只是瀏覽器上的一個空白屏幕。

我認為這與您的最終腳本標簽與所有 JavaScript 代碼所在的位置有關。 將所有代碼移動到正文標記中,它應該可以工作。 為了將來參考,我建議您創建一個單獨的 JavaScript 文件並在那里執行所有 JavaScript 代碼,然后將該文件放入您的 HTML 中。 它只是讓它更干凈。

<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