Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas></canvas>
              
            
!

CSS

              
                body {
    margin: 0;
    overflow: hidden;
}
.absCanvas {
    position: absolute;
    top: 0;
    left: 0;
    display: none;
    transform: translate(0px, 0px);
    transition: transform 0.15s ease-in;
}
              
            
!

JS

              
                const canvas = document.querySelector("canvas"),
	ctx = canvas.getContext("2d");
    
var newCanvas1,
	newCtx1,
    newCanvas2,
    newCtx2;

const primary1 = "rgba(104, 0, 0, 1)",
	secondary1 = "rgba(126, 139, 185, 1)",
    bg1 = "rgba(20, 64, 87, 1)";

const primary2 = "rgba(0, 0, 0, 1)",
	secondary2 = "rgba(211, 211, 211, 1)",
    bg2 = "rgba(255, 255, 255, 1)";

var width,
	height,
	centerX,
	centerY,
	smallerDimen,
    circleSize;

var canvasData,
	inCoords,
    exitCoords;

var state = "waiting";
    
function sizeCanvas() {
	width = canvas.width = newCanvas1.width = newCanvas2.width = window.innerWidth;
	height = canvas.height = newCanvas1.height = newCanvas2.height = window.innerHeight;
    centerX = width / 2;
	centerY = height / 2;
    smallerDimen = Math.min(width, height);
}

function drawNormalState() {
	document.body.style.backgroundColor = bg1;
    
	// Color the bg
    ctx.fillStyle = bg1;
    ctx.fillRect(0, 0, width, height);

    // Color the circle
    circleSize = smallerDimen / 4;
    ctx.beginPath();
    ctx.arc(centerX, centerY, circleSize, 0, Math.PI * 2, true);
    ctx.fillStyle = primary1;
    ctx.fill();
    ctx.lineWidth = 3;
    ctx.strokeStyle = secondary1;
    ctx.stroke();
    ctx.closePath();

    // Color the triangle
    ctx.beginPath();
    ctx.moveTo(centerX + smallerDimen / 17, centerY - smallerDimen / 10);
    ctx.lineTo(centerX + smallerDimen / 17, centerY + smallerDimen / 10);
    ctx.lineTo(centerX - smallerDimen / 9, centerY);
    ctx.fillStyle = secondary1;
    ctx.fill();
    ctx.closePath();
}

function drawAltState() {
    document.body.style.backgroundColor = bg2;
   
	ctx.clearRect(0, 0, width, height);

    // Color the circle
    circleSize = smallerDimen / 4;
    ctx.beginPath();
    ctx.arc(centerX, centerY, circleSize, 0, Math.PI * 2, true);
    ctx.fillStyle = primary2;
    ctx.fill();
    ctx.lineWidth = 3;
    ctx.strokeStyle = secondary2;
    ctx.stroke();
    ctx.closePath();

    // Color the triangle
    ctx.beginPath();
    ctx.moveTo(centerX + smallerDimen / 17, centerY - smallerDimen / 10);
    ctx.lineTo(centerX + smallerDimen / 17, centerY + smallerDimen / 10);
    ctx.lineTo(centerX - smallerDimen / 9, centerY);
    ctx.fillStyle = secondary2;
    ctx.fill();
    ctx.closePath();
}

function screenshot() {
	canvasData = ctx.getImageData(0, 0, width, height).data;
}

function getEndPoints(startX, startY, xDiff, yDiff, maxX, maxY) {
	let currX = startX, 
    	currY = startY;
    while(currX > 0 && currY > 0 && currX < maxX && currY < maxY) {
    	currX += xDiff;
        currY += yDiff;
    }
    let points = {
    	firstPoint: [currX, currY]
    };
    
    currX = startX;
    currY = startY;
    while(currX > 0 && currY > 0 && currX < maxX && currY < maxY) {
    	currX -= xDiff;
        currY -= yDiff;
    }
    points.secondPoint = [currX, currY];
    
    return points;
}

// From http://paulbourke.net/geometry/pointlineplane/javascript.txt
function intersect(point1, point2, point3, point4) {
	let x1 = point1[0], 
    	y1 = point1[1], 
        x2 = point2[0], 
        y2 = point2[1], 
        x3 = point3[0], 
        y3 = point3[1], 
        x4 = point4[0], 
        y4 = point4[1];
    
  	// Check if none of the lines are of length 0
	if((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {
		return false;
	}

	let denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));

	// Lines are parallel
	if(denominator === 0) {
		return false;;
	}

	let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator;
	let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator;

	// is the intersection along the segments
	if(ua < 0 || ua > 1 || ub < 0 || ub > 1) {
		return false;
	}

    // Return a object with the x and y coordinates of the intersection
    let x = x1 + ua * (x2 - x1);
	let y = y1 + ua * (y2 - y1);

	return [x, y];
}

var reverse;
function splitCanvas(canvas, width, height, points) {
    let origin = [0, 0],
    	xBound = [width, 0],
        xyBound = [width, height],
        yBound = [0, height];
    
    let polygon = [origin];
    
    if(points.firstPoint[0] < 0 || points.firstPoint[1] > height || (points.firstPoint[0] > width && points.secondPoint[1] < 0) || (points.firstPoint[1] > height && points.secondPoint[0] > width)) {
    	reverse = false;
    } else {
    	reverse = true;
    }
    
    // Work clockwise from 0,0, adding points to our polygon as appropriate
    
    // Check intersect with top bound
    let topIntersect = intersect(origin, xBound, points.firstPoint, points.secondPoint);
    if(topIntersect) {
    	polygon.push(topIntersect);
    }
    if(!topIntersect) {
		polygon.push(xBound);
	}
    
    // Check intersect with right
    let rightIntersect = intersect(xBound, xyBound, points.firstPoint, points.secondPoint);
    if(rightIntersect) {
    	polygon.push(rightIntersect);
    }
    if((!topIntersect && !rightIntersect)
    || (topIntersect && rightIntersect)) {
    	polygon.push(xyBound);
    }
    
    // Check intersect with bottom
    let bottomIntersect = intersect(xyBound, yBound, points.firstPoint, points.secondPoint);
    if(bottomIntersect) {
    	polygon.push(bottomIntersect);
    }
    if((topIntersect && bottomIntersect)
    || (topIntersect && rightIntersect)) {
    	polygon.push(yBound);
    }
    
    // Check intersect with left
    let leftIntersect = intersect(yBound, origin, points.firstPoint, points.secondPoint);
    if(leftIntersect) {
    	polygon.push(leftIntersect);
    }
    
    if(state === "waiting") {
    	drawNormalState();
    } else if(state === "particles") {
    	drawAltState();
    }
    
    newCtx1.clearRect(0, 0, width, height);
    newCtx1.save();
    newCtx1.drawImage(canvas, 0, 0);
    newCtx1.globalCompositeOperation = 'destination-in';
    newCtx1.beginPath();
    newCtx1.moveTo(polygon[0][0], polygon[0][1]);
    for(let item = 1; item < polygon.length; item++) {
        newCtx1.lineTo(polygon[item][0], polygon[item][1]);
    }
    newCtx1.closePath();
    newCtx1.fillStyle = "rgba(0, 0, 0, 1)";
    newCtx1.fill();
    newCtx1.restore();
    
    newCtx2.clearRect(0, 0, width, height);
    newCtx2.save();
    newCtx2.drawImage(canvas, 0, 0);
    newCtx2.globalCompositeOperation = 'destination-out';
    newCtx2.beginPath();
    newCtx2.moveTo(polygon[0][0], polygon[0][1]);
    for(let item = 1; item < polygon.length; item++) {
        newCtx2.lineTo(polygon[item][0], polygon[item][1]);
    }
    newCtx2.closePath();
    newCtx2.fillStyle = "rgba(0, 0, 0, 1)";
    newCtx2.fill();
    newCtx2.restore();
}

function getPerpPoints(startX, startY, angle, dist) {
	return [
    	[(Math.sin(angle) * dist + startX), (-Math.cos(angle) * dist + startY)], 
        [(-Math.sin(angle) * dist + startX), (Math.cos(angle) * dist + startY)]
    ];
}

var angle;
function drawLines(endPoints) {
	// Make vertices from endPoints
    angle = Math.atan2(endPoints.firstPoint[1] - endPoints.secondPoint[1], endPoints.firstPoint[0] - endPoints.secondPoint[0]);
    
    let perpStartPoints1 = getPerpPoints(endPoints.firstPoint[0], endPoints.firstPoint[1], angle, 8);
    let perpStartPoints2 = getPerpPoints(endPoints.firstPoint[0], endPoints.firstPoint[1], angle, 16);
    
    let perpEndPoints1 = getPerpPoints(endPoints.secondPoint[0], endPoints.secondPoint[1], angle, 8);
    let perpEndPoints2 = getPerpPoints(endPoints.secondPoint[0], endPoints.secondPoint[1], angle, 16);
    
    let vertices = [
    	[
        	endPoints.firstPoint,
            endPoints.secondPoint
        ], 
	    [
        	perpStartPoints1[0],
            perpEndPoints1[0]
        ], 
	    [
        	perpStartPoints1[1],
            perpEndPoints1[1]
        ], 
	    [
        	perpStartPoints2[0],
            perpEndPoints2[0]
        ], 
        [
        	perpStartPoints2[1],
            perpEndPoints2[1]
        ]
    ];
    
    // calcWaypoints
    let points = calcWaypoints(vertices);
    
    // Start animation function
    animateLines(points, 0, 0);
}

function calcWaypoints(vertices) {
    var waypoints = [];
    for (var i = 0; i < vertices.length; i++) {
        var pt0 = vertices[i][0];
        var pt1 = vertices[i][1];
        var dx = pt1[0] - pt0[0];
        var dy = pt1[1] - pt0[1];
        let arr = [];
        let numPoints = 10;
        
        for (var j = 0; j < numPoints; j++) {
            var x = pt0[0] + dx * j / numPoints;
            var y = pt0[1] + dy * j / numPoints;
            arr.push({
                x: x,
                y: y
            });
        }
        arr.push({x: vertices[i][1][0], y: vertices[i][1][1] });
        
        waypoints.push(arr);
    }
    return waypoints;
}

function animateLines(points, loc, frame) {
	drawNormalState(true);
    if(typeof points[0][loc + 1] !== "undefined") {
        requestAnimationFrame(function() {
        	animateLines(points, loc + 1, frame + 1);
        });
    } else if(loc === points[0].length - 1) {
    	if(state === "lines") {
            requestAnimationFrame(function() {
                animateLines(points, loc, frame + 1);
            });
        } 
    }
    
    if(frame % 5 !== 0 && state === "lines") {
        for(let i = 0; i < points.length; i++) {
            ctx.beginPath();
            ctx.strokeStyle = "rgb(255, 255, 255)";
            ctx.moveTo(points[i][0].x, points[i][0].y);
            ctx.lineTo(points[i][loc].x, points[i][loc].y);
            ctx.stroke();
        }
    }
}

var particles = [];
function createParticles() {
	state = "particles";
    splitCanvas(canvas, width, height, endPoints);
    
    let startX = (inCoords[0] + exitCoords[0]) / 2,
    	startY = (inCoords[1] + exitCoords[1]) / 2;
    
    let particleEndPoints = getPerpPoints(startX, startY, angle, (smallerDimen / 7));
    let numParticles = 25;
    let maxAngle = 70;
    let noise = (smallerDimen / 10);
    for(let i = 0; i < numParticles; i++) {
		let particle = new Particle();
        particle.startX = startX;
        particle.startY = startY;
        particle.endX = particleEndPoints[0][0] + (noise / 2 - Math.random() * noise);
        particle.endY = particleEndPoints[0][1] + (noise / 2 - Math.random() * noise);
        if(reverse) {
        	particle.endX = particleEndPoints[1][0] + (noise / 2 - Math.random() * noise);
        	particle.endY = particleEndPoints[1][1] + (noise / 2 - Math.random() * noise);
        }
        particle.rotationAngle = maxAngle / 2 - maxAngle * Math.random();
        particle.opacity = 1 - (maxAngle / 2 - Math.abs(particle.rotationAngle)) / (maxAngle / 2);
        particle.radius = (smallerDimen / 35) * particle.opacity;
        particle.ctx = newCtx1;
        particles.push(particle);
    }
    for(let i = 0; i < numParticles; i++) {
		let particle = new Particle();
        particle.startX = startX;
        particle.startY = startY;
        particle.endX = particleEndPoints[1][0] + (noise / 2 - Math.random() * noise);
        particle.endY = particleEndPoints[1][1] + (noise / 2 - Math.random() * noise);
        if(reverse) {
        	particle.endX = particleEndPoints[0][0] + (noise / 2 - Math.random() * noise);
        	particle.endY = particleEndPoints[0][1] + (noise / 2 - Math.random() * noise);
        }
        particle.rotationAngle = maxAngle / 2 - maxAngle * Math.random();
        particle.opacity = 1 - (maxAngle / 2 - Math.abs(particle.rotationAngle)) / (maxAngle / 2);
        particle.radius = (smallerDimen / 35) * particle.opacity;
        particle.ctx = newCtx2;
        particles.push(particle);
    }
    
    startTime = Date.now();
    animateParticles();
}

var startTime;
function animateParticles() {
	if(state === "particles") {
    	splitCanvas(canvas, width, height, endPoints);
        
    	particles.forEach(particle => {
        	let percent = (Date.now() - startTime) / 900;
            if(percent < 1)
        		particle.draw(percent);
            else 
            	particle.draw(1);
        });
        
        requestAnimationFrame(animateParticles);
    }
}

var endPoints;
function processCoords(enteredCoords, exitCoords) {
	state = "lines";
    
	let xDiff = enteredCoords[0] - exitCoords[0],
        yDiff = enteredCoords[1] - exitCoords[1];

    endPoints = getEndPoints(exitCoords[0], exitCoords[1], xDiff, yDiff, width, height);
    
    splitCanvas(canvas, width, height, endPoints);
    
    // Draw the fancy white lines
    drawLines(endPoints);
    
    // Move our split canvases along the line
    animateCanvases(enteredCoords, exitCoords);
}

function animateCanvases(enteredCoords, exitCoords) {
	let xDiff = enteredCoords[0] - exitCoords[0],
        yDiff = enteredCoords[1] - exitCoords[1];
    
    // Keep direction, dampen distance based on circle size
    let magnitude = Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
    let xAmnt = xDiff / magnitude * (circleSize * 0.8),
    	yAmnt = yDiff / magnitude * (circleSize * 0.8);
    
    setTimeout(function() {
    	newCanvas1.style.display = "block";
    	newCanvas2.style.display = "block";
        canvas.style.display = "none";
        
        newCanvas1.style.transform = `translate(0px, 0px)`;
        newCanvas2.style.transform = `translate(0px, 0px)`;
    	
        setTimeout(function() {
        	state = "moving";
            ctx.clearRect(0, 0, width, height);

            newCanvas1.style.transform = `translate(${xAmnt}px, ${yAmnt}px)`;
            newCanvas2.style.transform = `translate(${-xAmnt}px, ${-yAmnt}px)`;
        }, 50);
    }, 400);
}

function reset() {
    particles = [];
    
    state = "waiting";
    newCanvas1.style.display = "none";
    newCanvas2.style.display = "none";
    canvas.style.display = "block";
    
    document.body.style.backgroundColor = bg1;
    
    inCoords = undefined;
    exitCoords = undefined;
    
    drawNormalState(true);
}

function handleMousemove(e) {
	if(state === "waiting") {
        let x = Math.floor(e.pageX),
            y = Math.floor(e.pageY),
            dataIndex = (y * width + x) * 4;

        if(typeof inCoords === "undefined"
        && canvasData[dataIndex] === 104
        && canvasData[dataIndex + 1] === 0
        && canvasData[dataIndex + 2] === 0) {
            inCoords = [x, y];
        } 
        else if(typeof inCoords === "object"
        && canvasData[dataIndex] === 20
        && canvasData[dataIndex + 1] === 64
        && canvasData[dataIndex + 2] === 87) {
            exitCoords = [x, y];

            processCoords(inCoords, exitCoords);
        }
    }
}

const EaseOut = power => t => 1 - Math.abs(Math.pow(t-1, power))
var Particle = function() {
    this.draw = percent => {
    	let currX = this.startX + EaseOut(3)(percent) * (this.endX - this.startX),
        	currY = this.startY + EaseOut(3)(percent) * (this.endY - this.startY);
    	
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.translate(this.startX, this.startY);
      	this.ctx.rotate(this.rotationAngle * Math.PI / 180);
      	this.ctx.translate(-this.startX, -this.startY);
        this.ctx.arc(currX, currY, this.radius, 0, Math.PI * 2);
        this.ctx.fillStyle = `rgba(0, 0, 0, ${this.opacity * (1 - percent) + 0.2})`;
        this.ctx.fill();
        this.ctx.closePath();
        this.ctx.restore();
    }
}

function handleResize() {
	sizeCanvas();
    if(state !== "particles") {
    	drawNormalState();
        screenshot();
    } else {
    	drawAltState();
    }
}

function init() {
	newCanvas1 = document.createElement("canvas");
    newCanvas1.id = "newCanvas1";
    newCanvas1.className = "absCanvas";
    newCanvas1.width = width;
    newCanvas1.height = height;
    newCanvas1.addEventListener("transitionend", function() {
    	setTimeout(function() {
        	drawAltState(false);
    		splitCanvas(canvas, width, height, endPoints);
            drawAltState(true);
            createParticles();
        }, 300);
        setTimeout(reset, 1100);
    });
    document.body.appendChild(newCanvas1);
    newCtx1 = newCanvas1.getContext("2d");
    
    newCanvas2 = document.createElement("canvas");
    newCanvas2.id = "newCanvas2";
    newCanvas2.className = "absCanvas";
    newCanvas2.width = width;
    newCanvas2.height = height;
    document.body.appendChild(newCanvas2);
    newCtx2 = newCanvas2.getContext("2d");
    
    sizeCanvas();
    drawNormalState(true);
    screenshot();
    window.addEventListener("mousemove", handleMousemove);
    window.addEventListener("touchstart", handleMousemove);
    window.addEventListener("resize", handleResize);
}

init();



              
            
!
999px

Console