cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <head>
	<title>Cantor Set</title>
</head>
<body>
	<canvas></canvas>
	<script src="cantor.js" type="text/javascript"></script>
</body>

            
          
!
            
              body {
		width: 100%;
		height: 100vh;
		margin: 0;
		padding: 0;
	}

	canvas {
	    margin: auto;
	}
            
          
!
            
              "use strict";

var canvas = document.querySelector('canvas');
var context = canvas.getContext("2d");

const pixelRatio = Math.round(window.devicePixelRatio) || 1; // used to render high res image on retina screens
const barHeight = 30;
const level = 8;

function fitToContainer() {
    canvas.style.width  = '100%';
    canvas.width        = canvas.offsetWidth * pixelRatio;
    canvas.style.height = barHeight * 2 * level / pixelRatio + 'px';
    canvas.height       = canvas.offsetHeight * pixelRatio;

    context.strokeStyle = "#000";
    context.lineWidth = barHeight;

    drawCantor(level, level, 0, canvas.width);
}

fitToContainer();
window.addEventListener('resize', fitToContainer);

function drawCantor(level, max_level, x_start, x_end) {
    // only generate levels 1 - 13; hard to see levels beyond 13
    if (level < 1 || level > 13) return;

    // draw level
    context.beginPath();
    var y = barHeight/2 + (max_level - level) * barHeight * 2;
    context.moveTo(x_start, y);
    context.lineTo(x_end, y);
    context.strokeStyle = "hsl(" + (360 - 120*level/max_level) + ",100%,30%)";
    context.stroke();
    context.closePath();

    drawCantor(level - 1, max_level, x_start,  x_start + (x_end - x_start)/3); // left
    drawCantor(level - 1, max_level, x_start + 2/3*(x_end - x_start), x_end);  // right
}
            
          
!
999px
Loading ..................

Console