-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcanvas.js
113 lines (94 loc) · 2.5 KB
/
canvas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
An example drawing 3D shapes by combining small
modules and the Canvas2D API.
*/
var drawTriangles = require('draw-triangles-2d')
var createApp = require('canvas-loop')
var createTorus = require('primitive-torus')
var createConfetti = require('./confetti-mesh')
var clamp = require('clamp')
var colors = [
'hsl(80, 50%, 50%)',
'hsl(380, 50%, 50%)',
'hsl(180, 50%, 50%)'
]
// get a Canvas2D context
var canvas = document.querySelector('.canvas')
if (!canvas) {
canvas = document.body.appendChild(document.createElement('canvas'))
}
var ctx = canvas.getContext('2d', { alpha: false })
// disable right-click
canvas.oncontextmenu = function () {
return false
}
// set up our 3D scene (a list of 3D meshes)
var meshes = [
createTorus({
majorRadius: 0.3,
minorRadius: 0.05,
majorSegments: 4,
minorSegments: 3
}),
createConfetti(25, 0.5),
createConfetti(15, 0.75)
]
// a convenience utility for basic 3D camera math
var camera = require('perspective-camera')({
fov: 50 * Math.PI / 180,
position: [0, 0, 1],
near: 0.00001,
far: 100
})
// set up our input controls
var controls = require('../')({
position: camera.position,
element: canvas,
distanceBounds: [1, 100],
distance: 1.5
})
preventScroll()
// create a full-screen render loop for our canvas
var app = createApp(canvas, {
scale: window.devicePixelRatio
}).start()
app.on('tick', function () {
var width = app.shape[0]
var height = app.shape[1]
// update controls and easings
controls.update()
controls.copyInto(camera.position, camera.direction, camera.up)
// update camera viewport and matrices
var viewport = [0, 0, width, height]
camera.viewport = viewport
camera.update()
// draw our mesh
ctx.save()
ctx.scale(app.scale, app.scale)
ctx.fillStyle = '#1B1B23'
ctx.fillRect(0, 0, width, height)
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.lineWidth = clamp(1.5 / controls.distance, 0.25, 2)
meshes.forEach(function (mesh, i) {
ctx.strokeStyle = colors[i % colors.length]
drawMesh(ctx, camera, mesh)
})
ctx.restore()
})
function drawMesh (ctx, camera, mesh) {
// project the 3D points into 2D screen-space
var positions = mesh.positions.map(function (point) {
var pos = camera.project(point)
pos[1] = app.shape[1] - pos[1] // use inverted Y like OpenGL
return pos
})
ctx.beginPath()
drawTriangles(ctx, positions, mesh.cells)
ctx.stroke()
}
function preventScroll () {
canvas.addEventListener('touchstart', function (ev) {
ev.preventDefault()
})
}