Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Canvas 2D template</title>
- <style>
- body {
- margin: 0;
- }
- canvas {
- display: block;
- }
- </style>
- </head>
- <body>
- <canvas id="canvas"></canvas>
- </body>
- <script>
- let canvas = document.getElementById("canvas");
- // Store context of our canvas
- let c = canvas.getContext("2d");
- // Define width and height
- canvas.width = innerWidth;
- canvas.height = innerHeight;
- let canvasMidX = canvas.width / 2;
- let canvasMidY = canvas.height / 2;
- // Define core vars
- let mouse = {
- x: innerWidth / 2,
- y: innerHeight / 2
- };
- let colorArray = [
- '#45a57c',
- '#b1044e',
- '#71e0c9',
- '#e41e70'
- ];
- let objectToUpdate = [];
- let restarting = false;
- // Setup core events
- addEventListener('resize', () => {
- canvas.width = innerWidth;
- canvas.height = innerHeight;
- });
- addEventListener('mousemove', (event) => {
- mouse.x = event.clientX;
- mouse.y = event.clientY;
- })
- addEventListener('click', () => {
- restarting = true;
- });
- // Utility functions
- function randomIntFromRange(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min)
- }
- function randomInArray(array) {
- return array[Math.floor(Math.random() * array.length)]
- }
- function getDistance(x1, y1, x2, y2) {
- let xDistance = x2 - x1;
- let yDistance = y2 - y1;
- return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
- }
- // Script
- function Object(x, y, radius, color) {
- this.x = x;
- this.y = y;
- this.radius = radius;
- this.color = color;
- this.lifeTime = 0;
- this.update = function(time) {
- let random = Math.floor(Math.random() * 4 + 1);
- let x = this.x, y = this.y;
- switch(random) {
- case 1:
- x+= 5;
- break;
- case 2:
- x -= 5;
- break;
- case 3:
- y+= 5;
- break;
- case 4:
- y-=5;
- break;
- }
- if(x > 0 || x < canvas.width) this.x = x;
- if(y > 0 || y < canvas.height) this.y = y;
- this.draw();
- };
- this.draw = function() {
- c.beginPath();
- c.fillStyle = this.color;
- c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
- c.fill();
- c.closePath();
- }
- }
- // Core functions
- function init() {
- let ellipse = new Object(canvasMidX, canvasMidY, 2, "#000");
- objectToUpdate.push({id: "ellipse", object: ellipse});
- animate();
- }
- let appLifeTime = 0;
- function animate() {
- requestAnimationFrame(animate);
- //c.clearRect(0, 0, canvas.width, canvas.height);
- c.fillStyle = 'rgba(255, 255, 255, 0.01)';
- c.fillRect(0, 0, canvas.width, canvas.height);
- // code goes here
- appLifeTime ++;
- objectToUpdate.forEach(e => {
- e.object.update(appLifeTime);
- })
- }
- init();
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement