Published
Edited
Apr 30, 2021
Insert cell
md`# Yanghui Triangle`
Insert cell
{
var context = DOM.context2d(width, height)
var colorRainbow = d3.interpolateRainbow;
// var colorRainbow = d3.interpolateSinebow;
var fonts = []
var tan = Math.tan;
var PI = Math.PI;

function generate(deep, h, delta, midX, midY) {
while (deep >= 0) {
for (var i = 0; i <= deep; i++) {
var fontNum = C(i, deep);
var coord = layoutX(deep, midX, midY, h, delta, i)
var color = colorRainbow(i / 60);
fonts.push({
font: fontNum,
x: coord[0],
y: coord[1],
color: color
})
}
deep--;
}
}

function layoutX(n, midX, midY, h, delta, index) {
var x0 = midX - h * n / tan(delta);
var y = h * n + midY;
var x = x0 + diffX(delta, h) * index;
return [x, y];
}

function diffX(delta, h) {
return h * 2 / tan(delta);
}

function render() {
context.beginPath();
fonts.forEach(drawFont)
context.stroke();
}

function drawFont(item) {
context.fillStyle = item.color;
// context.fillStyle = "rgb(255, 120, 71)";
context.textAlign = "center";
context.textBaseline = "middle";
var fontSize = adapt(item.font + '');
context.font = fontSize + "px Times New Roman"
context.fillText(item.font, item.x, item.y);
}

function adapt(font) {
var fontSize = 24 - font.length * 2;
return fontSize >= 5 ? fontSize : 5;
}
generate(22, 22, PI / 4, width / 2, 40);
render();
return context.canvas
}
Insert cell
/*
* @param {*} s 起始数字
* @param {*} c 底部数字
*/
function factorial(s, c){
var val = 1;
while(s >= c){
val = val * s--;
}
return val;
}
//
Insert cell
function permutationCombination(low, top){
return parseInt(factorial(top, top- low + 1, 1) / factorial(low, 1, 1));
}
Insert cell
C = permutationCombination
Insert cell
width = 1000
Insert cell
height = 1000
Insert cell
d3 = require('d3@5')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more