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.

            
              <canvas id="canvas-main"></canvas>

<p id="help-text">r: reset, d: toggle debug drawing</p>
            
          
!
            
              html, body { font-size: 100%; }
body {
	font-family: sans-serif;
	
	color: rgba(255, 255, 255, 0.4);
}

#canvas-main {
	position: absolute;
	top: 0; right: 0;
	bottom: 0; left: 0;
	
	z-index: -1000;
	
	background: radial-gradient(circle closest-corner, rgb(12, 0, 31), rgb(25, 1, 64));
	
	cursor: crosshair;
}

#help-text
{
	position: absolute;
	bottom: 0; left: 0; right: 0;
	text-align: center;
}
            
          
!
            
              "use strict";

class Renderer
{
	constructor(canvas)
	{
		this.canvas = canvas;
		this.context = canvas.getContext("2d");

		this.smoothLine = new SmoothLine();
		/*this.smoothLine.add([
			new Vector(138, 330),
			new Vector(161, 10),
			new Vector(561, 111),
			new Vector(890, 254),
			new Vector(1088, 254),
			new Vector(1152, 130),
			new Vector(1186, 55),
			new Vector(1230, 21)
		]);*/
		this.debugDrawing = true;

		this.crossHairSize = 15;
		this.crossHairWidth = 3;
		this.crossHairStroke = "rgba(85, 105, 238, 0.5)";

		this.interCrossHairSize = 8;
		this.interCrossHairWidth = 2;
		this.interCrossHairStroke = "rgba(238, 85, 122, 0.5)";

		this.trackWindowSize();
		this.trackMouse();
		this.trackKeyboard();
		
		this.nextFrame();
	}

	nextFrame()
	{
		this.update();
		this.render(this.canvas, this.context);
		//requestAnimationFrame(this.nextFrame.bind(this));
	}

	update()
	{

	}

	render(canvas, context)
	{
		context.clearRect(0, 0, canvas.width, canvas.height);

		context.lineCap = "round";

		if (this.debugDrawing)
		{
			// Show all the points that the user has clicked
			for (let i = 0; i < this.smoothLine.points.length; i++) {
				this.renderCrossHair(canvas, context, this.smoothLine.points[i], this.crossHairSize, this.crossHairWidth, this.crossHairStroke)
			}

			// Show all the extra interpolated points
			for (let i = 0; i < this.smoothLine.interpolatedPoints.length; i++)
			{
				context.save();
				context.translate(
					this.smoothLine.interpolatedPoints[i].x,
					this.smoothLine.interpolatedPoints[i].y
				);
				context.rotate(Math.PI / 4);

				this.renderCrossHair(canvas, context, new Vector(0, 0), this.interCrossHairSize, this.interCrossHairWidth, this.interCrossHairStroke);

				context.restore();
			}
		}

		context.lineWidth = 1;
		context.strokeStyle = "white";
		this.renderSmoothLine(canvas, context);

		context.lineWidth = 4;
		context.strokeStyle = "rgba(255, 255, 255, 0.3)";
		this.renderSmoothLine(canvas, context);
		context.lineWidth = 6;
		context.strokeStyle = "rgba(255, 255, 255, 0.2)";
		this.renderSmoothLine(canvas, context);
		context.lineWidth = 6;
		context.strokeStyle = "rgba(255, 255, 255, 0.05)";
		this.renderSmoothLine(canvas, context);
	}

	renderSmoothLine(canvas, context)
	{
		context.beginPath();
		context.moveTo(
			this.smoothLine.points[0].x,
			this.smoothLine.points[0].y
		);
		this.smoothLine.line(context, 16);
		context.stroke();
	}

	renderCrossHair(canvas, context, position, size, width, stroke)
	{
		context.save();
		context.translate(position.x, position.y);
		context.beginPath();
		context.moveTo(0, -size);
		context.lineTo(0, size);
		context.moveTo(-size, 0);
		context.lineTo(size, 0);

		context.strokeStyle = stroke;
		context.lineWidth = width;
		context.stroke();

		context.restore();
	}

	trackMouse()
	{
		document.body.addEventListener("mouseup", this.mouseHandler.bind(this));
		document.body.addEventListener("touchend", this.mouseHandler.bind(this));
	}
	
	mouseHandler(event)
	{
		this.smoothLine.add(new Vector(event.pageX, event.pageY));
		
		this.render(this.canvas, this.context);
	}

	trackKeyboard()
	{
		document.body.addEventListener("keyup", (function(event) {
			switch (event.keyCode)
			{
				case 82: // r
					this.smoothLine = new SmoothLine();
					this.nextFrame();
					break;

				case 68: // d
					this.debugDrawing = this.debugDrawing ? false : true;
					this.nextFrame();
					break;
			}
		}).bind(this));
	}

	/////////////////////////////////////////////////

	/**
	 * Updates the canvas size to match the current viewport size.
	 */
	matchWindowSize()
	{
		this.canvas.width = window.innerWidth;
		this.canvas.height = window.innerHeight;

		//this.nextFrame();
	}

	/**
	 * Makes the canvas size track the window size.
	 */
	trackWindowSize()
	{
		this.matchWindowSize();
		window.addEventListener("resize", this.matchWindowSize.bind(this));
	}
}

class SmoothLine
{
	constructor()
	{
		this.points = [];
		this.interpolatedPoints = [];
		this.bezierCurves = [];

		this.lastPointLength = -1;
	}

	add(point)
	{
		if (Array.isArray(point))
			this.points.push(...point);
		else
			this.points.push(point);
	}

	interpolateOnce(points, time)
	{
		// Input validation checks
		if (time < 0 || time > 1)
			throw new Error(`The time specified was out of bounds! It should be between 0 and 1, but a value of ${time} was provided.`);
		if (!Array.isArray(points))
			throw new Error("THe points provided are not in an array!");
		if (points.length < 3)
			throw new Error("A minimum of 3 points are required to draw a smooth line.");

		var result = [];
		// Loop over all the points, except the last one
		for (let i = 0; i < points.length - 1; i++) {
			// Find the difference between the current point and the next one along
			// To get the vector of the line between 2 points, you do b - a for the points a and b.
			let difference = points[i + 1].clone().subtract(points[i]);

			// Multiply the line's vector by the time in order to extract a percentage along the line
			difference.multiply(time);

			// Add the first point on to put the vector back in the right place,
			// and then add it to the interpolated pionts array.
			// It's important to add the first control point on again here as we
			// made the vector relative to 0 in order to perform the
			// interpolation rather than relative to the first point on the line
			// as it should be.
			result.push(difference.add(points[i]));
		}

		return result;
	}

	line(context, segmentCount)
	{
		if (this.points.length < 3)
			throw new Error(`At least 3 points are required to draw a smooth line, but only ${this.points.length} points are currently specified.`);

		if (this.lastPointLength !== this.points.length)
		{
			// Reset the bezier curve cache
			this.bezierCurves = [];

			this.interpolatedPoints = this.interpolateOnce(this.points, 0.5);
			// Loop over every point except the frst & last ones
			for (let i = 1; i < this.points.length - 1; i++)
			{
				let nextPointSet = [
					this.interpolatedPoints[i - 1],
					this.points[i],
					this.interpolatedPoints[i]
				];

				// If this is the first iteration, make the first point of the bezier curve the first point that we were given
				if (i == 1)
					nextPointSet[0] = this.points[0];
				// If this is the last iteration, make the end point of the bezier curve the last point we were given
				if (i == this.points.length - 2)
					nextPointSet[2] = this.points[this.points.length - 1];
				// The above 2 checks are needed to make sure that the smooth line starts and ends at the points that we were given

				let nextBezier = new BezierCurve(nextPointSet);
				this.bezierCurves.push(nextBezier);
			}
		}

		// Spin through all the bezier curves and get them to add themselves to the current path
		for (let i = 0; i < this.bezierCurves.length; i++)
			this.bezierCurves[i].curve(context, segmentCount);

		// Update the cached poits length
		this.lastPointLength = this.points.length;
	}
}

window.addEventListener("load", function(event) {
	var canvas = document.getElementById("canvas-main"),
		renderer = new Renderer(canvas);
	renderer.nextFrame();
	window.renderer = renderer;
});
            
          
!
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