удаление сценария js со страницы html - PullRequest
0 голосов
/ 20 сентября 2018

<!DOCTYPE html5>
<html>

<head>
  <title>disturbed</title>

  <script>
    window.onload = function() {
      // create the canvas
      var canvas = document.createElement("canvas"),
        c = canvas.getContext("2d");
      var particles = {};
      var particleIndex = 0;
      var particleNum = 15;

      // set canvas size
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      // add canvas to body
      document.body.appendChild(canvas);

      // style the canvas
      c.fillStyle = "black";
      c.fillRect(0, 0, canvas.width, canvas.height);

      function Particle() {
        this.x = canvas.width / 2;
        this.y = canvas.height / 2;
        this.vx = Math.random() * 10 - 5;
        this.vy = Math.random() * 10 - 5;
        this.gravity = 0.3;
        particleIndex++;
        particles[particleIndex] = this;
        this.id = particleIndex;
        this.life = 0;


        this.maxLife = Math.random() * 30 + 60;


        this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
      }

      Particle.prototype.draw = function() {
        this.x += this.vx;
        this.y += this.vy;


        if (Math.random() < 0.1) {
          this.vx = Math.random() * 10 - 5;
          this.vy = Math.random() * 10 - 5;
        }

        this.life++;
        if (this.life >= this.maxLife) {
          delete particles[this.id];
        }

        c.fillStyle = this.color;
        //c.fillRect(this.x, this.y, 5, 10);
        c.beginPath();
        c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
        c.fill();
      };

      setInterval(function() {
        //normal setting before drawing over canvas w/ black background
        c.globalCompositeOperation = "source-over";
        c.fillStyle = "rgba(0,0,0,0.5)";
        c.fillRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < particleNum; i++) {
          new Particle();
        }

        // c.globalCompositeOperation = "darken";

        for (var i in particles) {
          particles[i].draw();
        }
      }, 30);
    };
  </script>


</head>

<body>
</body>

</html>

Все приведенные ниже коды верны, но их всего два, я хочу, чтобы их было проще, а не заполнять.то, что я хочу сделать, это сделать скрипт, который у меня есть, в отдельный файл, такой как "everything.js", чтобы я мог загрузить его в свой основной html-файл, просто вызвав основные функции, такие как частиц () в, window.onload =функция (), которая будет на главной странице.Причина в том, что я хочу добавить этот скрипт ко многим html-страницам и не хочу снова и снова копировать весь длинный скрипт в мой код.Пожалуйста, ответьте на это, это было бы очень полезно.

Ответы [ 2 ]

0 голосов
/ 20 сентября 2018

HTML:

<!DOCTYPE html5>
<html>

<head>
  <title>disturbed</title>   
</head>

<body>

<script src="toto.js" type="text/javascript"></script>
  <script type="text/javascript">
    window.onload = function() {
        Particle();
    };
  </script>
</body>

</html>

toto.js:

//create the canvas
var canvas = document.createElement("canvas"),
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;

// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// add canvas to body
document.body.appendChild(canvas);

// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);

function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;


this.maxLife = Math.random() * 30 + 60;


this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}

Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;


if (Math.random() < 0.1) {
    this.vx = Math.random() * 10 - 5;
    this.vy = Math.random() * 10 - 5;
}

this.life++;
if (this.life >= this.maxLife) {
    delete particles[this.id];
}

c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
c.fill();
};

setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
    new Particle();
}

// c.globalCompositeOperation = "darken";

for (var i in particles) {
    particles[i].draw();
}
}, 30);
0 голосов
/ 20 сентября 2018

Я вижу, у вас проблема с областью действия.

Переменные передаются от сценария к сценарию.Тем не менее, в вашем случае вы объявляете Particle внутри window.onload, чтобы он определялся только внутри него, и вы не сможете использовать его где-либо еще.

Правильный способ экспортировать ваш скрипт в отдельный файл будетобъявить Particle в области действия всего сценария, как в:

// anything.js
function Particle() {
    ...
}

Обратите внимание, что вам нужно немного переписать, так как я вижу, что вы используете переменные, такие как canvas (чтоопределены только в области window.onload) внутри кода Particle.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...