HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<canvas id="gfx"></canvas>
<div id="error"></div>
html,
body {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font-family: "Source Sans Pro", Helvetica, sans-serif;
vertical-align: baseline;
background: #000;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
color: #fff;
text-align: center;
}
code {
font-family: monospace;
}
// 🔎 Check out the blog post:
// https://alain.xyz/blog/raw-webgpu
// 🟦 Shaders
const vertWgsl = `
struct VSOut {
@builtin(position) Position: vec4<f32>,
@location(0) color: vec3<f32>,
};
@vertex
fn main(@location(0) inPos: vec3<f32>,
@location(1) inColor: vec3<f32>) -> VSOut {
var vsOut: VSOut;
vsOut.Position = vec4<f32>(inPos, 1.0);
vsOut.color = inColor;
return vsOut;
}`;
const fragWgsl = `
@fragment
fn main(@location(0) inColor: vec3<f32>) -> @location(0) vec4<f32> {
return vec4<f32>(inColor, 1.0);
}
`;
// 🌅 Renderer
// 📈 Position Vertex Buffer Data
const positions = new Float32Array([
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0,
0.0, 1.0, 0.0
]);
// 🎨 Color Vertex Buffer Data
const colors = new Float32Array([
1.0, 0.0, 0.0, // 🔴
0.0, 1.0, 0.0, // 🟢
0.0, 0.0, 1.0 // 🔵
]);
// 📇 Index Buffer Data
const indices = new Uint16Array([ 0, 1, 2 ]);
class Renderer {
canvas: HTMLCanvasElement;
// ⚙️ API Data Structures
adapter: GPUAdapter;
device: GPUDevice;
queue: GPUQueue;
// 🎞️ Frame Backings
context: GPUCanvasContext;
colorTexture: GPUTexture;
colorTextureView: GPUTextureView;
depthTexture: GPUTexture;
depthTextureView: GPUTextureView;
// 🔺 Resources
positionBuffer: GPUBuffer;
colorBuffer: GPUBuffer;
indexBuffer: GPUBuffer;
vertModule: GPUShaderModule;
fragModule: GPUShaderModule;
pipeline: GPURenderPipeline;
commandEncoder: GPUCommandEncoder;
passEncoder: GPURenderPassEncoder;
constructor(canvas) {
this.canvas = canvas;
}
// 🏎️ Start the rendering engine
async start() {
if (await this.initializeAPI()) {
this.resizeBackings();
await this.initializeResources();
this.render();
}
else {
canvas.style.display = "none";
document.getElementById("error").innerHTML = `
<p>Doesn't look like your browser supports WebGPU.</p>
<p>Try using any chromium browser's canary build and go to <code>about:flags</code> to <code>enable-unsafe-webgpu</code>.</p>`
}
}
// 🌟 Initialize WebGPU
async initializeAPI(): Promise<boolean> {
try {
// 🏭 Entry to WebGPU
const entry: GPU = navigator.gpu;
if (!entry) {
return false;
}
// 🔌 Physical Device Adapter
this.adapter = await entry.requestAdapter();
// 💻 Logical Device
this.device = await this.adapter.requestDevice();
// 📦 Queue
this.queue = this.device.queue;
} catch (e) {
console.error(e);
return false;
}
return true;
}
// 🍱 Initialize resources to render triangle (buffers, shaders, pipeline)
async initializeResources() {
// 🔺 Buffers
let createBuffer = (arr: Float32Array | Uint16Array, usage: number) => {
// 📏 Align to 4 bytes (thanks @chrimsonite)
let desc = {
size: (arr.byteLength + 3) & ~3,
usage,
mappedAtCreation: true
};
let buffer = this.device.createBuffer(desc);
const writeArray =
arr instanceof Uint16Array
? new Uint16Array(buffer.getMappedRange())
: new Float32Array(buffer.getMappedRange());
writeArray.set(arr);
buffer.unmap();
return buffer;
};
this.positionBuffer = createBuffer(positions, GPUBufferUsage.VERTEX);
this.colorBuffer = createBuffer(colors, GPUBufferUsage.VERTEX);
this.indexBuffer = createBuffer(indices, GPUBufferUsage.INDEX);
// 🖍️ Shaders
const vsmDesc: any = {
code: vertWgsl
};
this.vertModule = this.device.createShaderModule(vsmDesc);
const fsmDesc: any = {
code: fragWgsl
};
this.fragModule = this.device.createShaderModule(fsmDesc);
// ⚗️ Graphics Pipeline
// 🔣 Input Assembly
const positionAttribDesc: GPUVertexAttribute = {
shaderLocation: 0, // [[attribute(0)]]
offset: 0,
format: 'float32x3'
};
const colorAttribDesc: GPUVertexAttribute = {
shaderLocation: 1, // [[attribute(1)]]
offset: 0,
format: 'float32x3'
};
const positionBufferDesc: GPUVertexBufferLayout = {
attributes: [positionAttribDesc],
arrayStride: 4 * 3, // sizeof(float) * 3
stepMode: 'vertex'
};
const colorBufferDesc: GPUVertexBufferLayout = {
attributes: [colorAttribDesc],
arrayStride: 4 * 3, // sizeof(float) * 3
stepMode: 'vertex'
};
// 🌑 Depth
const depthStencil: GPUDepthStencilState = {
depthWriteEnabled: true,
depthCompare: 'less',
format: 'depth24plus-stencil8'
};
// 🦄 Uniform Data
const pipelineLayoutDesc = { bindGroupLayouts: [] };
const layout = this.device.createPipelineLayout(pipelineLayoutDesc);
// 🎭 Shader Stages
const vertex: GPUVertexState = {
module: this.vertModule,
entryPoint: 'main',
buffers: [positionBufferDesc, colorBufferDesc]
};
// 🌀 Color/Blend State
const colorState: GPUColorTargetState = {
format: 'bgra8unorm',
writeMask: GPUColorWrite.ALL
};
const fragment: GPUFragmentState = {
module: this.fragModule,
entryPoint: 'main',
targets: [colorState]
};
// 🟨 Rasterization
const primitive: GPUPrimitiveState = {
frontFace: 'cw',
cullMode: 'none',
topology: 'triangle-list'
};
const pipelineDesc: GPURenderPipelineDescriptor = {
layout,
vertex,
fragment,
primitive,
depthStencil
};
this.pipeline = this.device.createRenderPipeline(pipelineDesc);
}
// ↙️ Resize Canvas, frame buffer attachments
resizeBackings() {
// ⛓️ Canvas Context
if (!this.context) {
this.context = this.canvas.getContext('webgpu');
const canvasConfig: GPUCanvasConfiguration = {
device: this.device,
alphaMode: "opaque",
format: 'bgra8unorm',
usage:
GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
};
this.context.configure(canvasConfig);
}
const depthTextureDesc: GPUTextureDescriptor = {
size: [this.canvas.width, this.canvas.height, 1],
dimension: '2d',
format: 'depth24plus-stencil8',
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
};
this.depthTexture = this.device.createTexture(depthTextureDesc);
this.depthTextureView = this.depthTexture.createView();
}
// ✍️ Write commands to send to the GPU
encodeCommands() {
let colorAttachment: GPURenderPassColorAttachment = {
view: this.colorTextureView,
clearValue: { r: 0, g: 0, b: 0, a: 1 },
loadOp: 'clear',
storeOp: 'store'
};
const depthAttachment: GPURenderPassDepthStencilAttachment = {
view: this.depthTextureView,
depthClearValue: 1,
depthLoadOp: 'clear',
depthStoreOp: 'store',
stencilClearValue: 0,
stencilLoadOp: 'clear',
stencilStoreOp: 'store',
};
const renderPassDesc: GPURenderPassDescriptor = {
colorAttachments: [colorAttachment],
depthStencilAttachment: depthAttachment
};
this.commandEncoder = this.device.createCommandEncoder();
// 🖌️ Encode drawing commands
this.passEncoder = this.commandEncoder.beginRenderPass(renderPassDesc);
this.passEncoder.setPipeline(this.pipeline);
this.passEncoder.setViewport(
0,
0,
this.canvas.width,
this.canvas.height,
0,
1
);
this.passEncoder.setScissorRect(
0,
0,
this.canvas.width,
this.canvas.height
);
this.passEncoder.setVertexBuffer(0, this.positionBuffer);
this.passEncoder.setVertexBuffer(1, this.colorBuffer);
this.passEncoder.setIndexBuffer(this.indexBuffer, 'uint16');
this.passEncoder.drawIndexed(3, 1);
this.passEncoder.end();
this.queue.submit([this.commandEncoder.finish()]);
}
render = () => {
// ⏭ Acquire next image from context
this.colorTexture = this.context.getCurrentTexture();
this.colorTextureView = this.colorTexture.createView();
// 📦 Write and submit commands to queue
this.encodeCommands();
// ➿ Refresh canvas
requestAnimationFrame(this.render);
};
}
// Main
const canvas = document.getElementById('gfx') as HTMLCanvasElement;
canvas.width = canvas.height = 640;
const renderer = new Renderer(canvas);
renderer.start();
Also see: Tab Triggers