如何使js代码输出在特定DIV背景下运行

时间:2019-05-30 20:21:18

标签: javascript wordpress

我从Codepen遇到了一个不错的JS,它输出弹跳球https://codepen.io/rglazebrook/pen/JbxaI
我尝试将其用作网页中特定div的背景,但是当我使用该代码时,输​​出将显示在网站页脚下(如果您浏览此空白页面http://www.doronwolf.com/home2019/并向下滚动,您会看到跳动已成功加载,但仅在页脚下)
,那么如何使js代码输出在页面内运行,最好在页面内而不是在页脚下的特定div(称为“ herosection”)内运行?在下面,

您可以看到js代码,但请注意,它取决于外部脚本,可以在此处找到:https://rawgithub.com/soulwire/sketch.js/master/js/sketch.min.js

var particles = [],
particleCount = 200;
Particle = function(x,y) {
  this.x = x;
  this.y = y;
  this.radius = random(3,30);
  this.rgba = 'rgba('+floor(random(0,255))+','+floor(random(0,255))+','+floor(random(0,255))+','+random(.1,.8)+')';
  this.vx = random(-2,2);
  this.vy = random(-2,2);

  // Draw our particle to the canvas.
  this.draw = function(ctx) {
    ctx.fillStyle = this.rgba;
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.radius,0,TWO_PI);
    ctx.fill();
  };

  // Update our position.
  this.update = function(ctx) {
    this.x += this.vx;
    this.y += this.vy;
    // Bounce off edges.
    if(this.x + this.radius > ctx.width) {
      this.vx *= -1;
      this.x = ctx.width - this.radius;
    }
    if(this.x - this.radius < 0) {
      this.vx *= -1;
      this.x = this.radius;
    }
    if(this.y + this.radius > ctx.height) {
      this.vy *= -1;
      this.y = ctx.height - this.radius;
    }
    if(this.y - this.radius < 0) {
      this.vy *= -1;
      this.y = this.radius;
    }        
  }
};

var sketch = Sketch.create({
setup: function() {
var i = particleCount;
while(i--) {
  var p = new Particle(random(0, this.width),random(0, this.height));
  particles.push(p);
}
 },
update: function() {
var i = particleCount;
while(i--) { 
  particles[i].update(this);
}
},
draw: function() {
var i = particleCount;
while(i--) {
  particles[i].draw(this);
}
}
});    

1 个答案:

答案 0 :(得分:0)

仅使用sketchjs librarie并不是简单的方法。尝试将其包装在p5框架中,他们为此提供了帮助。

我使用进行了基本定位

container: document.getElementById("YOURID") fullscreen: false, width: 3000, height: 400,  作为Sketch.create()函数的选项

link to pen