html_append_p5js

by niuuin

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

<div class="content">
  <div>123</div>
  <div id="p5Element"></div>
  <div>456</div>
</div>

CSS

body {
   padding: 0;
   margin: 0;
 }

 .content {
   width: 90%;
   margin: 0 auto;
 }

 canvas {
   max-width: 100%;
 }

JavaScript

let cav;
let x = 0
let y = 0;
let speedX;
let speedY;

let p5Element = document.querySelector('#p5Element');
let canvasWidth = p5Element.offsetWidth;
let p5Width = canvasWidth;
let p5Height = canvasWidth * 0.6;

function setup() {
  cav = createCanvas(p5Width, p5Height);
  cav.parent('p5Element');
  speedX = random(-2, 4);
  speedY = random(-4, 1);
}

function draw() {
  background(0);
  move();
  fill(255);
  circle(x, y, canvasWidth * 0.1);
  // console.log(x);
}

function move() {
  if (x > width || x < 0) speedX *= -1;
  if (y > height || y < 0) speedY *= -1;
  x += speedX;
  y += speedY;
}

function windowResized() {
  //  setup();
  canvasWidth = p5Element.offsetWidth;
  p5Width = canvasWidth;
  p5Height = canvasWidth * 0.6;
  resizeCanvas(p5Width, p5Height);
}