Published
Edited
Aug 9, 2018
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
const w = width,
h = 200,
context = DOM.context2d(w, h);
const barPadding = 5,
barHeigth = h/cantor_depth - barPadding;
drawCantor(0 + barPadding, 0, w - barPadding*2, barHeigth, barPadding, context, 1);
return context.canvas;
}
Insert cell
function drawCantor(x, y, length, barHeight, barPadding, context, depth){
context.rect(x, y + barPadding/2, length, barHeight);
context.fill();
if (length > 1){
drawCantor(x, y + barHeight + barPadding, length/3, barHeight, barPadding, context, depth + 1);
drawCantor(x + 2*(length/3), y + barHeight + barPadding, length/3, barHeight, barPadding, context, depth + 1);
}
}
Insert cell
Insert cell
Insert cell
{
const w = 400,
h = w,
context = DOM.context2d(w,h);
generateSierpinskiCarpet(context);
return context.canvas;
}
Insert cell
generateSierpinskiCarpet = function(context){
const w = context.canvas.width,
h = context.canvas.height;

let squares = [];
squares.push(new Square(context, 0, 0, w, h));
for(let i = 0; i < sierpinski_depth; i++){
let next_squares = [];
for(let square of squares){
const side = square.side/3;
const [px, py] = [square.x, square.y];
next_squares.push(new Square(context, px, py, side));
next_squares.push(new Square(context, px + side, py, side));
next_squares.push(new Square(context, px + 2 * side, py, side));
next_squares.push(new Square(context, px, py + side, side));
next_squares.push(new Square(context, px + 2 * side, py + side, side));
next_squares.push(new Square(context, px, py + 2 * side, side));
next_squares.push(new Square(context, px + side, py + 2 * side, side));
next_squares.push(new Square(context, px + 2 * side, py + 2* side, side));
}
squares = squares.concat(next_squares); // key line
}
for(let square of squares){
square.show();
}
}
Insert cell
class Square{
constructor(context, x, y, side){
this.context = context;
this.x = x;
this.y = y;
this.side = side;
}
show(){
this.context.fillStyle = "white";
this.context.fillRect(this.x,this.y,this.side,this.side);
this.context.fillStyle = "brown";
this.context.fillRect(this.x + this.side/3,this.y + this.side/3,this.side/3,this.side/3);
}
}
Insert cell
Insert cell
Insert cell
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