### Install Dependencies with npm
Source: https://github.com/qrohlf/trianglify/blob/master/CONTRIBUTING.md
Installs project dependencies using npm, a package manager for Node.js. This command is typically run once after cloning the repository.
```bash
npm install
```
--------------------------------
### HTML Structure for Trianglify Demos
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
Defines basic CSS for the page layout and styles for the demo containers. This sets up the visual presentation for the Trianglify patterns.
```html
html, body {
margin: 0 0;
padding: 0 0;
text-align: center;
background: #000;
font-family: system-ui;
}
h1 {
font-size: 18px;
}
.demo {
background: #FFF;
display: inline-block;
padding: 20px;
margin: 20px;
}
```
--------------------------------
### Install Trianglify with npm/yarn
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Installs the Trianglify library using npm or yarn package managers. This is the recommended way to include Trianglify in your project.
```bash
npm install --save trianglify
```
--------------------------------
### Trianglify Basic Pattern Generation (JavaScript)
Source: https://github.com/qrohlf/trianglify/blob/master/examples/basic-web-example.html
Generates a basic Trianglify pattern with specified cell size and dimensions, rendering it to both SVG and Canvas elements. It uses the Trianglify library, which needs to be included in the HTML.
```javascript
const pattern = trianglify({
cellSize: 50,
width: window.innerWidth * 0.8,
height: (window.innerHeight - 4 * 30) / 4
});
// Render to SVG
document.body.appendChild(pattern.toSVG());
// Render to Canvas
document.body.appendChild(pattern.toCanvas());
```
--------------------------------
### Trianglify with Shadows Color Function
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
Illustrates the use of the 'shadows' color function in Trianglify to create a faux-3D effect. This function works best with subtle gradients and solid colors for optimal results.
```javascript
// Example 2: the shadows color function applies a faux-3d effect to the // pattern. This works best with subtle gradients and solid colors.
const shadows = trianglify({
seed,
width: 400,
height: 300,
cellSize: 15,
colorFunction: trianglify.colorFunctions.shadows()
})
addToPage(shadows, 'trianglify.colorFunctions.shadows()')
```
--------------------------------
### JavaScript Utility for HTML Tree Construction
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
A utility function 'h' to easily create HTML elements with attributes and children, simplifying the process of building the DOM. It's used here to append Trianglify patterns and descriptions to the page.
```javascript
const JITTER_FACTOR = 0.2 // utility for building up HTML trees
const h = (tagName, attrs = {}, children = []) => {
const elem = document.createElement(tagName)
attrs && Object.keys(attrs).forEach( k => attrs[k] !== undefined && elem.setAttribute(k, attrs[k]) )
children && children.forEach(c => elem.appendChild(c))
return elem
}
const addToPage = (pattern, description) => {
document.body.appendChild(h('div', {'class': 'demo'}, [ pattern.toCanvas(), h('h1', null, [document.createTextNode(description)]) ] ))
}
```
--------------------------------
### Trianglify with Sparkle Color Function
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
Demonstrates using Trianglify's built-in 'sparkle' color function to create a glitter-like effect by applying a jitter to the color gradients. The 'seed' ensures consistent pattern generation.
```javascript
const seed = 'pears' // Example 1: you can use the built-in color functions to customize the // color rendering of Trianglify. Here, we use the 'sparkle' color // function to apply a 10% jitter to the normal color gradients, which // will yield a glitter-like effect.
const sparkle = trianglify({
seed,
width: 400,
height: 300,
cellSize: 15,
colorFunction: trianglify.colorFunctions.sparkle(0.2)
})
addToPage(sparkle, 'trianglify.colorFunctions.sparkle(0.2)')
```
--------------------------------
### CSS Animation for Trianglify Color Stops
Source: https://github.com/qrohlf/trianglify/blob/master/examples/transparency-example.html
Defines CSS keyframes to animate the color of different stops in the Trianglify pattern. These animations are applied to specific IDs to create dynamic color transitions over time.
```css
html, body { margin: 0 0; padding: 0 0; text-align: center; font-size: 0; height: 100%; width: 100%; }
#gradient-rotate {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100vw;
height: 100vh;
}
#trianglify-overlay {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100vw;
height: 100vh;
}
#color-stop-1 {
-webkit-animation: change-color-1 12s ease-in-out infinite alternate;
animation: change-color-1 12s ease-in-out infinite alternate;
}
#color-stop-2 {
-webkit-animation: change-color-2 12s ease-in-out infinite alternate;
animation: change-color-2 12s ease-in-out infinite alternate;
}
#color-stop-3 {
-webkit-animation: change-color-3 12s ease-in-out infinite alternate;
animation: change-color-3 12s ease-in-out infinite alternate;
}
@keyframes change-color-1 {
0% { stop-color: #22C8F6; }
25% { stop-color: #ff0; }
50% { stop-color: #00ffcb; }
75% { stop-color: #70ff00; }
}
@keyframes change-color-2 {
0% { stop-color: #20C498; }
25% { stop-color: #ff00ad; }
350% { stop-color: #d480ff; }
75% { stop-color: #ff9200; }
}
@keyframes change-color-3 {
0% { stop-color: #189932; }
25% { stop-color: #c300cb; }
50% { stop-color: #5600d4; }
75% { stop-color: #ff46dc; }
}
```
--------------------------------
### Trianglify with Custom Radial Gradient Color Function
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
Demonstrates creating a custom color function for Trianglify to apply a radial gradient. This provides complete control over how polygons are colored, achieving effects like a gradient emanating from the center.
```javascript
// Example 4: you can write your own custom color function to have // total control over how the polygons are given color values. // // Here, we apply the xScale colors as a radial gradient:
// define a custom color function that applies a radial gradient:
const radialGradient = (radius) => ({centroid, xScale}) => {
const distanceFromCenter = Math.sqrt( Math.pow(200 - centroid.x, 2) + Math.pow(150 - centroid.y, 2) )
return(xScale(distanceFromCenter / radius))
}
// figure out the gradient radius required to cover the image dimensions:
const gradientRadius = Math.sqrt( Math.pow(400 / 2, 2) + Math.pow(300 / 2, 2) )
const radial = trianglify({
seed,
width: 400,
height: 300,
cellSize: 15,
colorFunction: radialGradient(gradientRadius)
})
addToPage(radial, 'custom radial gradient')
```
--------------------------------
### Trianglify with InterpolateLinear Color Function
Source: https://github.com/qrohlf/trianglify/blob/master/examples/color-function-example.html
Shows how to use the 'interpolateLinear' color function in Trianglify to control the dominance of x or y gradients. Higher bias values emphasize the x-gradient, while lower values emphasize the y-gradient.
```javascript
// Example 2: you can use the interpolateLinear color function to // customize how much the x or y gradient dominates the image. // Higher values for the bias will result in a more pronounced x-gradient, // while lower values will results in a more pronounced y-gradient
const interpolate = trianglify({
seed,
width: 400,
height: 300,
cellSize: 15,
colorFunction: trianglify.colorFunctions.interpolateLinear(0.1)
})
addToPage(interpolate, 'trianglify.colorFunctions.interpolateLinear(0.1)')
```
--------------------------------
### JavaScript Trianglify Pattern Generation
Source: https://github.com/qrohlf/trianglify/blob/master/examples/transparency-example.html
Generates an SVG Trianglify pattern dynamically using JavaScript. It configures the pattern with specific dimensions, color ranges, and cell size based on window dimensions, then appends the generated SVG to the document body.
```javascript
// set up the base pattern
const pattern = trianglify({
height: window.innerHeight,
width: window.innerWidth,
xColors: ['rgba(255, 255, 255, 0.1)', 'rgba(255, 255, 255, 1)'],
yColors: 'match',
cellSize: Math.ceil(window.innerWidth / 8)
});
var svg = pattern.toSVG();
svg.id = 'trianglify-overlay';
document.body.appendChild(svg);
```
--------------------------------
### Access Pattern Data Programmatically with Trianglify
Source: https://context7.com/qrohlf/trianglify/llms.txt
Demonstrates how to programmatically access the generated points, polygon data, and configuration options of a Trianglify pattern. This JavaScript example logs the number of points, individual point coordinates, polygon details (centroid, vertex indices, color), and pattern options like cell size and variance. The output is logged to the console.
```javascript
const trianglify = require('trianglify')
const pattern = trianglify({
width: 600,
height: 400,
cellSize: 100
})
// Access points array
console.log(`Generated ${pattern.points.length} points`)
pattern.points.forEach(([x, y], index) => {
console.log(`Point ${index}: (${x}, ${y})`)
})
// Access polygon data
pattern.polys.forEach((poly, index) => {
const { centroid, vertexIndices, color } = poly
console.log(`Polygon ${index}:`)
console.log(` Centroid: (${centroid.x}, ${centroid.y})`)
console.log(` Vertices: ${vertexIndices.join(', ')}`)
console.log(` Color: ${color.hex()}`)
})
// Access configuration
console.log(`Cell size: ${pattern.opts.cellSize}`)
console.log(`Variance: ${pattern.opts.variance}`)
```
--------------------------------
### Trianglify Stroke-Only Pattern (JavaScript)
Source: https://github.com/qrohlf/trianglify/blob/master/examples/basic-web-example.html
Generates a Trianglify pattern that only displays strokes, without any fill. This is useful for creating wireframe-like geometric designs. It renders the stroke-only pattern to both SVG and Canvas.
```javascript
const strokeOnly = trianglify({
cellSize: 75,
width: window.innerWidth * 0.8,
height: (window.innerHeight - 4 * 30) / 4,
fill: false,
strokeWidth: 1
});
document.body.appendChild(strokeOnly.toSVG());
document.body.appendChild(strokeOnly.toCanvas());
```
--------------------------------
### Create Circular Patterns with Custom Points in Trianglify
Source: https://context7.com/qrohlf/trianglify/llms.txt
Illustrates generating non-rectangular patterns in Trianglify by providing a custom array of points. This JavaScript example calculates points in a circular distribution and uses them to create a pattern. The output is a canvas element.
```javascript
const trianglify = require('trianglify')
// Generate circular point distribution
const width = 800
const height = 800
const centerX = width / 2
const centerY = height / 2
const radius = 300
const numPoints = 500
const points = []
for (let i = 0; i < numPoints; i++) {
const angle = (i / numPoints) * Math.PI * 2
const r = Math.sqrt(Math.random()) * radius
points.push([
centerX + r * Math.cos(angle),
centerY + r * Math.sin(angle)
])
}
const pattern = trianglify({
width,
height,
points,
xColors: 'Purples'
})
const canvas = pattern.toCanvas()
```
--------------------------------
### Generate SVG Background in Browser
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Generates an SVG background using Trianglify and appends it to the document body. This example assumes Trianglify has been loaded via a script tag. It dynamically sets the canvas size to the browser window's dimensions.
```html
```
--------------------------------
### Trianglify Custom Points Generation with JavaScript
Source: https://github.com/qrohlf/trianglify/blob/master/examples/custom-points-example.html
Generates a custom set of points using polar coordinates to create a spiral effect. These points are then used by Trianglify to generate a unique polygon pattern, which is rendered onto an HTML5 canvas. Requires the Trianglify library.
```javascript
const width = 700;
const height = 700;
// generate a spiral using polar coordinates
const points = [];
const NUM_POINTS = 150;
let r = 0;
const rStep = width / 2 / NUM_POINTS;
let theta = 0;
const thetaStep = Math.PI / NUM_POINTS * 18;
for (let i = 0; i < NUM_POINTS; i++) {
const x = width / 2 + r * Math.cos(theta);
const y = height / 2 + r * Math.sin(theta);
const point = [x, y];
points.push(point);
r += rStep;
theta = (theta + thetaStep) % (2 * Math.PI);
}
// apply trianglify to convert the points to polygons and apply the color
// gradient
var pattern = trianglify({
height,
width,
points
});
// use the toCanvas function to render the generated geometry to an HTML5
// canvas element
document.body.appendChild(pattern.toCanvas());
```
--------------------------------
### Generate SVG Background in Node.js
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Generates an SVG background image in a Node.js environment and saves it as a PNG file. This example requires the 'trianglify' and 'fs' modules. It creates a PNG stream from the canvas and pipes it to a file.
```javascript
const trianglify = require('trianglify')
const fs = require('fs')
const canvas = trianglify({
width: 1920,
height: 1080
}).toCanvas()
const file = fs.createWriteStream('trianglify.png')
canvas.createPNGStream().pipe(file)
```
--------------------------------
### Test and Compile Code with npm
Source: https://github.com/qrohlf/trianglify/blob/master/CONTRIBUTING.md
Runs code tests and compiles the project into trianglify.min.js. This command ensures code quality and prepares the distributable file.
```bash
npm run ci
```
--------------------------------
### API Usage: Initialize Trianglify Pattern
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Demonstrates how to initialize a Trianglify pattern with custom options. The `trianglify` function can be called directly after loading the library. It returns a `trianglify.Pattern` object.
```javascript
// load the library, either via a window global (browsers) or require call (node)
// in es-module environments, you can `import trianglify from 'trianglify'` as well
const trianglify = window.trianglify || require('trianglify')
const options = { height: 400, width: 600 }
const pattern = trianglify(options)
console.log(pattern instanceof trianglify.Pattern) // true
```
--------------------------------
### Generate Basic Trianglify Pattern to Canvas/PNG
Source: https://context7.com/qrohlf/trianglify/llms.txt
Generates a basic Trianglify pattern with default settings and demonstrates rendering it to a Canvas element for browser use or saving as a PNG file in Node.js. Requires the 'trianglify' and 'fs' modules.
```javascript
const trianglify = require('trianglify')
const pattern = trianglify({
width: 1920,
height: 1080
})
// In browser: append to DOM
document.body.appendChild(pattern.toCanvas())
// In Node.js: save as PNG
const fs = require('fs')
const file = fs.createWriteStream('output.png')
pattern.toCanvas().createPNGStream().pipe(file)
```
--------------------------------
### Include Trianglify via unpkg CDN
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Includes the Trianglify JavaScript library in your HTML file using the unpkg CDN. This makes the library available globally in the browser environment.
```html
```
--------------------------------
### Generate Trianglify Patterns with Random Colors
Source: https://context7.com/qrohlf/trianglify/llms.txt
Generates Trianglify patterns using random color palettes sourced from the Colorbrewer library. This snippet also shows how to access and log properties of the generated pattern, such as the number of points, triangles, centroid, and color of the first polygon.
```javascript
const trianglify = require('trianglify')
// Random colors with high variance for more dramatic effect
const pattern = trianglify({
width: 800,
height: 600,
cellSize: 100,
variance: 0.9,
xColors: 'random',
yColors: 'match'
})
// Access pattern properties
console.log(pattern.points.length) // Number of generated points
console.log(pattern.polys.length) // Number of triangles
console.log(pattern.polys[0].centroid) // { x: 50.2, y: 75.8 }
console.log(pattern.polys[0].color.hex()) // '#4a90e2'
```
--------------------------------
### Generate Reproducible Trianglify Patterns with Seeds
Source: https://context7.com/qrohlf/trianglify/llms.txt
Illustrates how to generate identical Trianglify patterns consistently by using a seed value. Creating two patterns with the same dimensions, seed, and color settings ensures that the output will be the same for both, facilitating reproducible designs.
```javascript
const trianglify = require('trianglify')
// Generate the same pattern every time with the same seed
const pattern1 = trianglify({
width: 600,
height: 400,
seed: 'blog-post-title-123',
xColors: 'Blues'
})
const pattern2 = trianglify({
width: 600,
height: 400,
seed: 'blog-post-title-123',
xColors: 'Blues'
})
// pattern1 and pattern2 will be identical
```
--------------------------------
### Trianglify SVG Rendering Options
Source: https://github.com/qrohlf/trianglify/blob/master/Readme.md
Defines options for customizing SVG output when using the `pattern.toSVG` or `pattern.toSVGTree` methods. Includes namespace inclusion and coordinate rounding.
```javascript
const svgOpts = {
// Include or exclude the xmlns='http://www.w3.org/2000/svg' attribute on
// the root