canvas实现彩色三角形随机布局效果代码

代码语言:html

所属分类:布局界面

代码描述:canvas实现彩色三角形随机布局效果代码

代码标签: canvas 彩色 三角形 随机 布局

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.container {
  height: 100%;
  overflow: hidden;
  position: absolute;
  width: 100%;
}
</style>


</head>

<body>
  <div class="container">
  <canvas></canvas>
</div>

      <script  >
// Find the canvas in the HTML document
const canvas = document.querySelector("canvas");

// Get the canvas 2D context
let ctx = canvas.getContext("2d");

// Add colours to an array, index 0 is the background
let colors = ["#f4f4f4", "#f8419b", "#fd4b4b", "#fc743a", "#fda400", "#feef16", "#8bd2d8", "#51c4d0", "#6d4b50"];

// Store the size for the triangles
let size = 0;

// Store the size of half a triangle
let half = 0;

// Track the offset value
let offset = 0;

// Track the values of x and y for centrally distributing the triangles
let x_value = 0;
let y_value = 0;

// Define function to run initiate the canvas
function init() {
  // Set the width of the canvas to match the window width
  canvas.width = window.innerWidth;
  // Set the height of the canvas to match the window height
  canvas.height = window.innerHeight;
  // Calculate the x and y values
  x_value = Math.PI / (canvas.width - size);
  y_value = Math.PI / (canvas.height + size + size);
  // Select the background colour
  ctx.fillStyle = colors[0];
  // Fill the canvas
  ctx.fillRect(0,0,canvas.width, canvas.height);
  // Set a random size for half the triangle
  half = getRandom(20, Math.round((canvas.width * 0.05) + 20));
  // Calculate the size by doubling the half size
  size = half * 2;
  // Traverse the height of the screen using the size variable
  for (let y = 0; y < canvas.height - size; y += size) {
    // Check the offset value
    if (offset) {
      // Reset the offset
      offset = 0;
    }
    // Otherwise the offset needs to be set
    else {
      // Set the offset to half of the size
      offset .........完整代码请登录后点击上方下载按钮下载查看

网友评论0