css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              html, body, canvas
	height: 100%
	width: 100%
	margin: 0

body
	background: #020c04

canvas
	position: absolute
	top: 50%
	left: 50%
	transform: translate(-50%, -50%)
	max-width: 640px
	max-height: 480px
	border: 36px solid #010301
	box-shadow: 0 0 48px 8px #010301

            
          
!
            
              const HORIZON_Y = 0.8;
const SPACING_Y = 2.2;
const SPACING_X = 32;
const SPACING_SCANLINES = 12;
const SKEW = 7;
const ACCELERATION = 0.005;
const X_DECELERATION = 0.002;
const MAX_Y_SPEED = 0.2;
const MIN_Y_SPEED = 0.02;
const MAX_X_SPEED = 0.1;
const P_GLITCH = 0.002;
const GLITCH_PAUSE_DURATION = [300, 800]; // min, max in ms.
const COLOR = [55, 255, 55];
const TITLE = 'CYBER PILOT';

const dynamicCtx = document.createElement('canvas').getContext('2d');
const staticCtx  = document.createElement('canvas').getContext('2d');
const screenCtx  = document.createElement('canvas').getContext('2d');
const ctxs = [dynamicCtx, staticCtx, screenCtx];

// Define and hydrate the state.
// The rest is filled onResize.
const state = {
	keys: {},
    ySpeed: MIN_Y_SPEED,
	xSpeed: 0,
    glitched: false,
    yOffset: 0,
    xOffset: 0,
};

function onResize () {
    const h = state.h = Math.min(480, window.innerHeight) * 2;
    const w = state.w = Math.min(640, window.innerWidth) * 2;
    const y0 = state.y0 = h * (1 - HORIZON_Y);
    state.nHorizontal =
        Math.pow((h * HORIZON_Y), 1 / SPACING_Y);
    state.nVertical = Math.ceil(w / SPACING_X);
    state.nScanlines = Math.ceil(h / SPACING_SCANLINES);
    
    // Update the DOM.
    ctxs.forEach(ctx => {
        ctx.canvas.height = state.h;
        ctx.canvas.width = state.w;
    });
    
    drawStatic();
};

function drawStatic () {
    const {h, w, y0, nVertical} = state;
    const ctx = staticCtx;
    
    ctx.clearRect(0, 0, w, h);
    
    // Fade the lines on the wall.
    const fade = ctx.createLinearGradient(0, 0, 0, y0);
    fade.addColorStop(0.0, 'rgba(0, 0, 0, 1)');
    fade.addColorStop(0.5, 'rgba(0, 0, 0, 0.65)');
    fade.addColorStop(1.0, 'rgba(0, 0, 0, 0)');
    ctx.fillStyle = fade;
    ctx.fillRect(0, 0, w, y0);

    // Draw title.
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = `rgba(${COLOR}, ${1/3})`;
    ctx.font = 'bold 20pt "Monoton", monospace';
    ctx.fillText(TITLE, w/2, y0/3.3);
    ctx.fillStyle = `rgba(${COLOR}, ${2/3})`;
    ctx.font = 'bold 30pt "Monoton", monospace';
    ctx.fillText(TITLE, w/2, y0/2.6);
    ctx.fillStyle = `rgba(${COLOR}, 1)`;
    ctx.font = 'bold 56pt "Monoton", monospace';
    ctx.fillText(TITLE, w/2, y0/1.8);
    
    drawScreenArtifacts();
}

function drawScreenArtifacts () {
    const {h, w} = state;
    const ctx = screenCtx;
    
    ctx.clearRect(0, 0, w, h);
    
    // Draw scanlines.
    const strokeOptions = {
        c1: 'rgba(44, 74, 44, 0.16)',
        c2: 'rgba(0, 10, 0, 0.16)',
    };
    for (let n = 0; n < state.nScanlines; ++n) {
        const y = n * SPACING_SCANLINES;
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(w, y);
        stroke(ctx, strokeOptions);
    }
    
    // Draw glow.
    ctx.beginPath();
    const glow = ctx.createRadialGradient(
        w / 2, h / 2, Math.max(w, h),
        w / 2, h / 2, SPACING_X * 1.5
    );
    glow.addColorStop(0.2, 'rgba(0, 0, 0, 0.16)');
    glow.addColorStop(1.0, `rgba(${COLOR}, 0.16)`);
    ctx.fillStyle = glow;
    ctx.fillRect(0, 0, w, h);
}

function drawDynamic () {
    const {h, w, y0, xSpeed, nVertical, nHorizontal, yOffset, xOffset} = state;
    const ctx = dynamicCtx;
    
    ctx.clearRect(0, 0, w, h);
    
    // Draw vertical lines.
    for (let n = 0; n <= nVertical; ++n) {
        ctx.beginPath();
        const x = (nVertical/2 - n);
        const x1 = (x + xOffset) * SPACING_X + w/2;
        const x2 = (x + xOffset) * SPACING_X * SKEW + w/2;
        ctx.beginPath();
        ctx.moveTo(x1, 0);
        ctx.lineTo(x1, y0);
        ctx.lineTo(x2, h);
        stroke(ctx);
    }
    
    // Draw horizontal lines.
    for (let n = 0; n < nHorizontal; n++) {
        const y = y0 + 2 + Math.pow(n + yOffset, SPACING_Y);
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(w, y);
        stroke(ctx);
    }
	
	// Draw spaceship.
	const tilt = -xSpeed/MAX_X_SPEED * Math.PI/6;
    ctx.beginPath();
    ctx.arc(w / 2, h / 2, SPACING_X * 1.5, tilt + Math.PI*5/16, tilt + Math.PI*11/16);
    ctx.lineTo(w / 2, h / 2);
    ctx.closePath();
    stroke(ctx);
}

function tick () {
    requestAnimationFrame(tick);
	
	const {keys, glitched, yOffset, xOffset} = state;
	let {ySpeed, xSpeed} = state;
	if (keys[37]) xSpeed += ACCELERATION;
    if (keys[38]) ySpeed += ACCELERATION;
    if (keys[39]) xSpeed -= ACCELERATION;
    if (keys[40]) ySpeed -= ACCELERATION;
	const xSpeedAbs = Math.abs(Math.min(MAX_X_SPEED, ySpeed, Math.max(-MAX_X_SPEED, -ySpeed, xSpeed)));
    state.ySpeed = Math.min(MAX_Y_SPEED, Math.max(MIN_Y_SPEED, ySpeed));
    state.xSpeed = Math.sign(xSpeed) * (xSpeedAbs - Math.min(xSpeedAbs, X_DECELERATION));
    state.yOffset = (yOffset + ySpeed) % 1;
	state.xOffset = (xOffset + xSpeed + 1) % 1;

    if (glitched) return;
    drawDynamic();
    
    if (Math.random() > P_GLITCH) return;
    drawGlitch();
}

function drawGlitch () {
    const {w, h} = state;
      
    dynamicCtx.drawImage(staticCtx.canvas, 0, 0);
    staticCtx.clearRect(0, 0, w, h);
    
    const fullImageData = dynamicCtx.getImageData(0, 0, w, h);
    const glitchOptions = {
        quality: 4,
        amount: 0,
        iterations: 2,
    };
    glitch(glitchOptions)
        .fromImageData(fullImageData)
        .toImageData()
        .then(imageData => {
            dynamicCtx.clearRect(0, 0, w, h);
            dynamicCtx.putImageData(imageData, 0, 0);
        })
        ;
    
    state.glitched = true;
    
    const [minDelay, maxDelay] = GLITCH_PAUSE_DURATION;
    const delay = minDelay + Math.random() * (maxDelay - minDelay);
    setTimeout(_ => {
        drawStatic();
        state.glitched = false;
    }, delay);
}

window.addEventListener('resize', throttle(onResize));
document.addEventListener('keydown', ({keyCode}) =>
	state.keys[keyCode] || (state.keys[keyCode] = true));
document.addEventListener('keyup', ({keyCode}) =>
	state.keys[keyCode] && (state.keys[keyCode] = false));

// Kick it off!
WebFont.load({
    active: function () {
        onResize();
        tick();
        ctxs.forEach(({canvas}) => {
            document.body.appendChild(canvas);
        });
    },
    classes: false,
    google: {
        families: ['Monoton'],
    },
});

// A thin white line gives us a nice glow-y effect.
function stroke (ctx, {
    w1 = 10,
    w2 = 2,
    c1 = `rgba(${COLOR}, 0.5)`,
    c2 = `rgb(${COLOR})`,
} = {}) {
    ctx.lineWidth = w1;
    ctx.strokeStyle = c1;
    ctx.stroke();
    ctx.lineWidth = w2;
    ctx.strokeStyle = c2;
    ctx.stroke();
}

// Throttles a function to RAF.
function throttle (cb) {
    let queued = false;
    
    return (...args) => {
        if (queued) return;
        
        queued = true;
        requestAnimationFrame(_ => {
            queued = false;
            cb(...args);
        });
    };
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console