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.
<!-- Copyright 2023 The MediaPipe Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
<h1>Face stylization using the MediaPipe FaceStylizer task</h1>
<!-- <section id="demos" class="invisible"> -->
<section id="demos">
<h2>Demo: Stylizing Images</h2>
<p>Select a style from the dropdown menu and click "Use style". Then <b>click on an image below</b> to see the style applied to the given face.</p>
<div id="styleDropdown">
<label for="styleSelector">Select a Face Stylization:</label>
<select id="styleSelector">
<option value="https://storage.googleapis.com/mediapipe-models/face_stylizer/blaze_face_stylizer/float32/latest/face_stylizer_oil_painting.task">Oil Painting</option>
<option value="https://storage.googleapis.com/mediapipe-models/face_stylizer/blaze_face_stylizer/float32/latest/face_stylizer_color_ink.task">Color Ink</option>
<option value="https://storage.googleapis.com/mediapipe-models/face_stylizer/blaze_face_stylizer/float32/latest/face_stylizer_color_sketch.task">Color Sketch</option>
</select>
<button id="changeStyle" class="mdc-button mdc-button--raised">
<span class="mdc-button__ripple"></span>
<span class="mdc-button__label">USE STYLE</span>
</button>
</div>
<div class="stylizeOnClick">
<img src="https://storage.googleapis.com/mediapipe-assets/portrait.jpg" width="100%" crossorigin="anonymous" title="Click to get detection!" />
</div>
<div class="stylizeOnClick">
<img src="https://assets.codepen.io/9177687/female-4572747_640.jpg" width="100%" crossorigin="anonymous" title="Click to get detection!" />
</div>
<h2>Demo: Webcam face stylizer detection</h2>
<p>Hold your face in front of your webcam, then click <b>Pause and stylize</b> to pause and trigger face stylization.</br>Click <b>enable webcam</b> below and grant access to the webcam if prompted.</p>
<div id="liveView" class="videoView">
<button id="webcamButton" class="mdc-button mdc-button--raised">
<span class="mdc-button__ripple"></span>
<span class="mdc-button__label">RUN WEBCAM</span>
</button>
<div style="position: relative;">
<video id="webcam" autoplay playsinline></video>
<canvas class="output_canvas" id="output_canvas"></canvas>
</div>
</div>
</section>
/* Copyright 2023 The MediaPipe Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/* Copyright 2022 The MediaPipe Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
@use "@material";
body {
font-family: helvetica, arial, sans-serif;
margin: 2em;
color: #3d3d3d;
--mdc-theme-primary: #007f8b;
--mdc-theme-on-primary: #f1f3f4;
}
h1 {
font-style: italic;
color: #ff6f00;
color: #007f8b;
}
h2 {
clear: both;
}
em {
font-weight: bold;
}
video {
clear: both;
display: block;
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
}
section {
opacity: 1;
transition: opacity 500ms ease-in-out;
}
header,
footer {
clear: both;
}
.removed {
display: none;
}
.invisible {
opacity: 0.2;
}
.note {
font-style: italic;
font-size: 130%;
}
.videoView,
.stylizeOnClick {
position: relative;
float: left;
width: 50%;
margin: 2% 1%;
cursor: pointer;
}
.videoView p,
.stylizeOnClick p {
position: absolute;
padding: 5px;
background-color: #007f8b;
color: #fff;
z-index: 2;
font-size: 12px;
margin: 0;
}
.canvas {
z-index: 1;
position: absolute;
pointer-events: none;
}
.output_canvas {
position: absolute;
top: 0;
left: 100%;
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
}
.stylizeOnClick {
z-index: 0;
}
.stylizeOnClick img {
width: 100%;
}
// Copyright 2022 The MediaPipe Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
FaceStylizer,
FilesetResolver,
MPImage
} from "https://cdn.skypack.dev/@mediapipe/tasks-vision@0.10.6";
const demosSection = document.getElementById("demos");
let faceStylizer: FaceStylizer;
let enableWebcamButton: HTMLButtonElement;
let webcamRunning: Boolean = false;
const videoWidth = 480;
// Before we can use FaceStylizer class we must wait for it to finish
// loading. Machine Learning models can be large and take a moment to
// get everything needed to run.
// async function runDemo() {
// Read more `CopyWebpackPlugin`, copy wasm set from "https://cdn.skypack.dev/node_modules" to `/wasm`
async function createFaceStylizer() {
const dropdown = document.getElementById("styleSelector");
const selectedOption = dropdown.options[dropdown.selectedIndex].value;
// Clean up any existing Face Stylizer instance
if (faceStylizer !== undefined) {
faceStylizer.close();
}
const vision = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.6/wasm"
);
faceStylizer = await FaceStylizer.createFromOptions(vision, {
baseOptions: {
modelAssetPath: selectedOption
}
});
}
createFaceStylizer();
const changeStyleButton = document.getElementById(
"changeStyle"
) as HTMLButtonElement;
changeStyleButton.addEventListener("click", createFaceStylizer);
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/********************************************************************
// Demo 1: Grab a bunch of images from the page and stylize them
// upon click.
********************************************************************/
// In this demo, we have put all our clickable images in divs with the
// CSS class 'stylizeOnClick'. Lets get all the elements that have
// this class.
const imageContainers = document.getElementsByClassName(
"stylizeOnClick"
) as HTMLCollectionOf<HTMLDivElement>;
// Now let's go through all of these and add a click event listener.
for (let i = 0; i < imageContainers.length; i++) {
// Add event listener to the child element whichis the img element.
imageContainers[i].children[0].addEventListener("click", handleClick);
}
// When an image is clicked, let's stylize it and display results!
async function handleClick(event) {
if (!faceStylizer) {
console.log("Wait for faceStylizer to load before clicking!");
return;
}
// Remove all face styles drawed before
const allCanvas = event.target.parentNode.getElementsByClassName("canvas");
for (var i = allCanvas.length - 1; i >= 0; i--) {
const n = allCanvas[i];
n.parentNode.removeChild(n);
}
// We can call faceStylizer.stylize as many times as we like with
// different image data each time. This returns a promise
// which we wait to complete and then call a function to
// draw the generated image.
// Add an element to let user know that stylization is taking place
const waitingText = document.createElement("p");
waitingText.setAttribute("class", "canvas");
waitingText.setAttribute("width", event.target.naturalWidth + "px");
waitingText.setAttribute("height", event.target.naturalHeight + "px");
waitingText.style.left = "calc(100% + 16px)";
waitingText.style.top = "0px";
waitingText.style.width = `${event.target.width / 3}px`;
waitingText.innerText = "Stylization in progress...";
event.target.parentNode.appendChild(waitingText);
await sleep(5);
const faceStylizerResult = faceStylizer.stylize(event.target);
const canvas = document.createElement("canvas") as HTMLCanvasElement;
canvas.setAttribute("class", "canvas");
canvas.setAttribute("width", event.target.naturalWidth + "px");
canvas.setAttribute("height", event.target.naturalHeight + "px");
canvas.style.left = "calc(100% + 16px)";
canvas.style.top = "0px";
canvas.style.width = `${event.target.width}px`;
canvas.style.height = `${event.target.height}px`;
event.target.parentNode.appendChild(canvas);
const ctx = canvas.getContext("2d");
ctx.putImageData(faceStylizerResult.getAsImageData(), 0, 0);
event.target.parentNode.removeChild(waitingText);
}
/********************************************************************
// Demo 2: Continuously grab image from webcam stream and stylize it.
********************************************************************/
const video = document.getElementById("webcam") as HTMLVideoElement;
const canvasElement = document.getElementById(
"output_canvas"
) as HTMLCanvasElement;
const canvasCtx = canvasElement.getContext("2d");
// Check if webcam access is supported.
function hasGetUserMedia() {
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}
// If webcam supported, add event listener to button for when user
// wants to activate it.
if (hasGetUserMedia()) {
enableWebcamButton = document.getElementById(
"webcamButton"
) as HTMLButtonElement;
enableWebcamButton.addEventListener("click", enableCam);
} else {
console.warn("getUserMedia() is not supported by your browser");
}
// Enable the live webcam view and start stylization.
function enableCam(event) {
if (!faceStylizer) {
console.log("Wait! faceStylizer not loaded yet.");
return;
}
if (webcamRunning === true) {
webcamRunning = false;
enableWebcamButton.innerText = "RUN WEBCAM";
video.pause();
predictWebcam();
} else {
webcamRunning = true;
enableWebcamButton.innerText = "PAUSE AND STYLIZE";
if (video.paused && video.played.length > 0) {
video.play();
} else {
// Activate the webcam stream.
navigator.mediaDevices
.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
});
}
}
}
let lastVideoTime = -1;
async function predictWebcam() {
const startTimeMs = performance.now();
const callback = (image: MPImage) => {
if (image) {
canvasElement.width = image.width;
canvasElement.height = image.height;
canvasCtx.putImageData(image.getAsImageData(), 0, 0);
}
};
// Stylize when Pause video
if (!webcamRunning && lastVideoTime !== video.currentTime) {
lastVideoTime = video.currentTime;
faceStylizer.stylize(video, callback);
}
}
Also see: Tab Triggers