html_append_p5js_Step-02
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: 80%;
margin: 0 auto;
}
canvas {
max-width: 100%;
}
JavaScript
let cav;
let p5Element = document.querySelector('#p5Element');
let canvasWidth = p5Element.offsetWidth;
let p5Width = canvasWidth;
let p5Height = canvasWidth * 0.6;
let x = 0;
let y = 0;
let speedX, speedY;
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, 90);
}
function move() {
if (x > width || x < 0) speedX *= -1;
if (y > height || y < 0) speedY *= -1;
x += speedX;
y += speedY;
}