
本文旨在提供一个将codepen项目成功部署到本地环境的专业教程,重点解决直接复制粘贴代码时遇到的外部依赖、css预处理器和javascript模块导入问题。我们将以一个mediapipe facelandmarker项目为例,详细讲解如何正确引入cdn资源、处理es模块导入,并提供完整的本地运行代码示例,确保项目功能在本地浏览器中正常运行。
CodePen等在线代码编辑平台为前端开发提供了极大的便利,用户可以快速编写、测试和分享HTML、CSS和JavaScript代码。然而,当尝试将这些项目直接复制到本地环境运行时,开发者常会遇到功能不正常的问题。这通常是由于以下几个原因:
本教程将以一个使用MediaPipe FaceLandmarker进行人脸关键点检测的CodePen项目为例,详细演示如何解决这些问题,使其在本地环境成功运行。
首先,在你的本地计算机上创建一个新的文件夹,例如my-codepen-project。在这个文件夹中,创建一个名为index.html的文件。所有代码都将整合到这个文件中,以便于演示和理解。
要使CodePen项目在本地正常运行,我们需要将HTML、CSS和JavaScript代码整合到index.html中,并特别注意处理所有外部依赖和模块导入。
项目的基本HTML结构应包含必要的head和body标签,以及元数据设置,如字符集、视口配置等。这些是现代网页开发的标准实践。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <title>Face Landmarker</title> <!-- 其他CSS和JS链接将在此处添加 --> </head> <body> <!-- 页面内容将在此处添加 --> </body> </html>
CodePen中的CSS通常会直接应用,但如果使用了预处理器(如Sass的@use),在本地需要进行调整。对于本例,CSS可以直接嵌入到<style>标签中,同时需要引入外部的Material Components Web CSS。
<head>
<!-- ...其他head内容... -->
<style>
/* CodePen中的CSS内容,去除预处理器指令(如@use "@material";)
并确保所有样式都直接可解析。
本例中的CSS是纯CSS,可以直接复制。
*/
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,
.detectOnClick,
.blend-shapes {
position: relative;
float: left;
width: 48%;
margin: 2% 1%;
cursor: pointer;
}
.videoView p,
.detectOnClick p {
position: absolute;
padding: 5px;
background-color: #007f8b;
color: #fff;
border: 1px dashed rgba(255, 255, 255, 0.7);
z-index: 2;
font-size: 12px;
margin: 0;
}
.highlighter {
background: rgba(0, 255, 0, 0.25);
border: 1px dashed #fff;
z-index: 1;
position: absolute;
}
.canvas {
z-index: 1;
position: absolute;
pointer-events: none;
}
.output_canvas {
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
}
.detectOnClick {
z-index: 0;
}
.detectOnClick img {
width: 100%;
}
.blend-shapes-item {
display: flex;
align-items: center;
height: 20px;
}
.blend-shapes-label {
display: flex;
width: 120px;
justify-content: flex-end;
align-items: center;
margin-right: 4px;
}
.blend-shapes-value {
display: flex;
height: 16px;
align-items: center;
background-color: #007f8b;
}
</style>
<!-- 引入Material Components Web CSS -->
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
<!-- 引入Material Components Web JS (在head中加载以确保样式正确应用) -->
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
</head>这是最关键的部分。CodePen中的JavaScript代码可能使用了ES模块(import语句),并且依赖于通过CDN加载的MediaPipe库。我们需要确保:
特别注意,原始问答中提供的[email protected]链接是Cloudflare的邮件保护机制,在本地直接复制会导致错误。我们需要将其替换为实际的CDN路径。根据CodePen项目,MediaPipe tasks-vision的正确CDN路径应为 https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0。
<body>
<h1>Face landmark detection using the MediaPipe FaceLandmarker task</h1>
<section id="demos" class="invisible">
<h2>Demo: Detecting Images</h2>
<p><b>Click on an image below</b> to see the key landmarks of the face.</p>
<div class="detectOnClick">
<img src="https://storage.googleapis.com/mediapipe-assets/portrait.jpg" width="100%" crossorigin="anonymous" title="Click to get detection!" />
</div>
<div class="blend-shapes">
<ul class="blend-shapes-list" id="image-blend-shapes"></ul>
</div>
<h2>Demo: Webcam continuous face landmarks detection</h2>
<p>Hold your face in front of your webcam to get real-time face landmarker detection.</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">ENABLE WEBCAM</span>
</button>
<div style="position: relative;">
<video id="webcam" style="position: abso" autoplay playsinline></video>
<canvas class="output_canvas" id="output_canvas" style="position: absolute; left: 0px; top: 0px;"></canvas>
</div>
</div>
<div class="blend-shapes">
<ul class="blend-shapes-list" id="video-blend-shapes"></ul>
</div>
</section>
<script type="module">
// 修正后的MediaPipe tasks-vision CDN导入路径
import vision from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0";
const { FaceLandmarker, FilesetResolver, DrawingUtils } = vision;
const demosSection = document.getElementById("demos");
const imageBlendShapes = document.getElementById("image-blend-shapes");
const videoBlendShapes = document.getElementById("video-blend-shapes");
let faceLandmarker;
let runningMode = "IMAGE"; // 初始运行模式
let enableWebcamButton; // HTMLButtonElement;
let webcamRunning = false; // Boolean = false;
const videoWidth = 480;
// Before we can use HandLandmarker 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() {
// 修正FilesetResolver的WASM路径
const filesetResolver = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm"
);
faceLandmarker = await FaceLandmarker.createFromOptions(filesetResolver, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task`,
delegate: "GPU"
},
outputFaceBlendshapes: true,
runningMode,
numFaces: 1
});
demosSection.classList.remove("invisible");
}
runDemo();
/********************************************************************
// Demo 1: Grab a bunch of images from the page and detection them
// upon click.
********************************************************************/
// In this demo, we have put all our clickable images in divs with the
// CSS class 'detectionOnClick'. Lets get all the elements that have
// this class.
const imageContainers = document.getElementsByClassName("detectOnClick");
// 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 detect it and display results!
async function handleClick(event) {
if (!faceLandmarker) {
console.log("Wait for faceLandmarker to load before clicking!");
return;
}
if (runningMode === "VIDEO") {
runningMode = "IMAGE";
await faceLandmarker.setOptions({ runningMode });
}
// Remove all landmarks 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 faceLandmarker.detect 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
// print out the results of the prediction.
const faceLandmarkerResult = faceLandmarker.detect(event.target);
const canvas = document.createElement("canvas");
canvas.setAttribute("class", "canvas");
canvas.setAttribute("width", event.target.naturalWidth + "px");
canvas.setAttribute("height", event.target.naturalHeight + "px");
canvas.style.left = "0px";
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");
const drawingUtils = new DrawingUtils(ctx);
for (const landmarks of faceLandmarkerResult.faceLandmarks) {
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_TESSELATION,
{ color: "#C0C0C070", lineWidth: 1 }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_RIGHT_EYE,
{ color: "#FF3030" }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_RIGHT_EYEBROW,
{ color: "#FF3030" }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_LEFT_EYE,
{ color: "#30FF30" }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_LEFT_EYEBROW,
{ color: "#30FF30" }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_FACE_OVAL,
{ color: "#E0E0E0" }
);
drawingUtils.drawConnectors(landmarks, FaceLandmarker.FACE_LANDMARKS_LIPS, {
color: "#E0E0E0"
});
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_RIGHT_IRIS,
{ color: "#FF3030" }
);
drawingUtils.drawConnectors(
landmarks,
FaceLandmarker.FACE_LANDMARKS_LEFT_IRIS,
{ color: "#30FF30" }
);
}
drawBlendShapes(imageBlendShapes, faceLandmarkerResult.faceBlendshapes);
}
/********************************************************************
// Demo 2: Continuously grab image from webcam stream and detect it.
********************************************************************/
const video = document.getElementById("webcam");
const canvasElement = document以上就是在本地运行CodePen项目:解决外部依赖与模块导入问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号