阅读视图
老外抢着当张雪机车代理,张雪机车全球订单狂飙
美计划用 “猎鹰重型”火箭发射欧航局火星车
海康威视增利不增收:去年净利同比增长近两成,创新业务贡献继续提升
蔚来回应ES9仍用隐藏式门把手:完全合规
国际海事组织:约有2万海员被困波斯湾
大屏开发必读:Scale/VW/Rem/流式/断点/混合方案全解析(附完整demo)
大屏适配终极指南:6 种主流方案实战对比
数据可视化大屏开发中,屏幕适配是最令人头疼的问题之一。本文通过 6 个完整 Demo,深度对比 Scale、VW/VH、Rem、流式布局、响应式断点、混合方案这 6 种主流方案的优缺点与适用场景。
前言
在开发数据可视化大屏时,你是否遇到过这些问题:
- 设计稿是 1920×1080,实际大屏是 3840×2160,怎么适配?
- 大屏比例不是 16:9,出现黑边或拉伸怎么办?
- 小屏幕上字体太小看不清,大屏幕上内容太空旷
- 图表、地图、视频等组件在不同尺寸下表现不一致
本文将通过 6 个完整的可交互 Demo,带你逐一攻克这些难题。
方案一:Scale 等比例缩放
核心原理
通过 CSS transform: scale() 将整个页面按屏幕比例缩放,是最简单直观的方案。
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;
function setScale() {
const scaleX = window.innerWidth / DESIGN_WIDTH;
const scaleY = window.innerHeight / DESIGN_HEIGHT;
const scale = Math.min(scaleX, scaleY);
screen.style.transform = `scale(${scale})`;
// 居中显示
const left = (window.innerWidth - DESIGN_WIDTH * scale) / 2;
const top = (window.innerHeight - DESIGN_HEIGHT * scale) / 2;
screen.style.left = left + 'px';
screen.style.top = top + 'px';
}
优缺点分析
优点:
- 完美还原设计稿比例
- 实现简单,几行代码搞定
- 字体、图表自动缩放,无需额外处理
- 兼容性好,不需要关注浏览器兼容性
缺点:
- 屏幕比例不符时出现黑边(如 4:3 屏幕)
- 小屏幕上字体会缩得很小,可能看不清
- 无法利用多余空间,浪费屏幕资源
适用场景
数据可视化大屏、监控中心大屏等需要精确还原设计稿的场景。
方案二:VW/VH 视口单位
核心原理
使用 CSS viewport 单位(vw/vh)代替 px,让元素根据视口尺寸自适应。
.container {
width: 50vw; /* 视口宽度的 50% */
height: 30vh; /* 视口高度的 30% */
font-size: 2vw; /* 字体随视口宽度变化 */
padding: 2vh 3vw; /* 内边距也自适应 */
}
优缺点分析
优点:
- 纯 CSS 方案,无 JS 依赖
- 充分利用全部屏幕空间,无黑边
- 无缩放导致的模糊问题
缺点:
- 计算公式复杂,需要手动换算
- 宽高难以协调,容易出现变形
- 单位换算易出错,维护成本高
适用场景
内容型页面、需要充分利用屏幕空间的场景。
方案三:Rem 动态计算
核心原理
根据视口宽度动态计算根字体大小,所有尺寸使用 rem 单位。
function setRem() {
const designWidth = 1920;
const rem = (window.innerWidth / designWidth) * 100;
document.documentElement.style.fontSize = rem + 'px';
}
// CSS 中使用 rem
.card {
width: 4rem; /* 设计稿 400px */
height: 2rem; /* 设计稿 200px */
font-size: 0.24rem; /* 设计稿 24px */
}
优缺点分析
优点:
- 计算相对直观(设计稿 px / 100 = rem)
- 兼容性最好,支持 IE9+
- 无缩放模糊问题
缺点:
- 依赖 JS 初始化,页面可能闪烁
- 高度处理困难,只能基于宽度适配
- 需要手动或使用工具转换单位
适用场景
移动端 H5 页面、PC 端后台系统。
方案四:流式/弹性布局
核心原理
使用百分比、Flexbox、Grid 等 CSS 原生能力实现响应式布局。
.dashboard {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.card {
display: flex;
flex-direction: column;
padding: 2%;
}
.chart {
flex: 1;
min-height: 200px;
}
优缺点分析
优点:
- 纯 CSS 方案,无任何依赖
- 自然响应式,适配各种屏幕
- 内容自适应,信息密度可变
缺点:
- 设计稿还原度低,无法精确控制
- 图表比例容易失控
- 空间利用率低,不够美观
适用场景
B 端后台系统、管理平台等以内容为主的页面。
方案五:响应式断点
核心原理
使用 @media 查询针对不同屏幕尺寸写多套样式规则。
/* 1920×1080 大屏 */
@media (min-width: 1920px) {
.container { width: 1800px; font-size: 24px; }
.grid { grid-template-columns: repeat(4, 1fr); }
}
/* 3840×2160 4K 屏 */
@media (min-width: 3840px) {
.container { width: 3600px; font-size: 48px; }
.grid { grid-template-columns: repeat(6, 1fr); }
}
/* 1366×768 小屏 */
@media (max-width: 1366px) {
.container { width: 1300px; font-size: 18px; }
.grid { grid-template-columns: repeat(3, 1fr); }
}
优缺点分析
优点:
- 精确控制各个分辨率的显示效果
- 字体可读性可控
- 适合有固定规格的大屏群
缺点:
- 代码量爆炸,维护极其困难
- 无法覆盖所有可能的分辨率
- 新增规格需要大量修改
适用场景
有固定规格的大屏群、展厅多屏展示系统。
方案六:混合方案(推荐)
核心原理
结合 Scale + Rem 的优点,既保证设计稿比例,又确保字体在小屏可读。
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;
const MIN_SCALE = 0.6; // 最小缩放限制
function adapt() {
const winW = window.innerWidth;
const winH = window.innerHeight;
// Scale 计算 - 保证整体比例
const scaleX = winW / DESIGN_WIDTH;
const scaleY = winH / DESIGN_HEIGHT;
const scale = Math.max(Math.min(scaleX, scaleY), MIN_SCALE);
// 应用 scale
screen.style.transform = `scale(${scale})`;
// Rem 计算 - 根据缩放比例调整根字体
// 当 scale < 1 时,增加根字体补偿
const baseRem = 100;
const fontScale = Math.max(scale, MIN_SCALE);
const rem = baseRem * fontScale;
document.documentElement.style.fontSize = rem + 'px';
}
优缺点分析
优点:
- 等比例缩放保证布局一致性
- 字体最小值保护,防止过小不可读
- 大屏清晰、小屏可读
- 兼顾视觉和体验
缺点:
- 需要 JS 支持
- 计算逻辑稍复杂
适用场景
通用推荐方案,适合绝大多数大屏开发场景。
方案对比一览表
| 方案 | 实现难度 | 设计稿还原度 | 响应式表现 | 小屏可读性 | 维护成本 | 推荐场景 |
|---|---|---|---|---|---|---|
| Scale | 简单 | 极高 | 一般 | 差 | 低 | 数据可视化大屏 |
| VW/VH | 中等 | 中等 | 好 | 中等 | 中等 | 内容型页面 |
| Rem | 中等 | 高 | 一般 | 中等 | 中等 | 移动端 H5 |
| 流式布局 | 简单 | 低 | 极好 | 好 | 低 | B 端后台系统 |
| 断点方案 | 复杂 | 中-高 | 好 | 好 | 极高 | 固定规格大屏群 |
| 混合方案 | 中等 | 高 | 好 | 好 | 中等 | 通用推荐 |
场景推荐速查
🖥️ 数据可视化大屏 / 监控中心
需要精确还原设计稿,图表比例严格保持,像素级对齐。
推荐: Scale 等比例缩放(接受黑边)或 混合方案
示例: 企业展厅大屏、运营监控看板
📊 B 端后台 / 管理系统
内容为主,需要充分利用屏幕空间,信息密度要高。
推荐: 流式布局 或 VW/VH 方案
示例: CRM 系统、数据管理平台
🌐 多端适配 / 响应式网站
需要覆盖手机、平板、电脑、大屏等多种设备。
推荐: 响应式断点 + 流式布局
示例: 企业官网、数据门户
完整 Demo 代码
以下是 6 种大屏适配方案的完整可运行代码,保存为 HTML 文件后可直接在浏览器中打开体验。
Demo 1: Scale 等比例缩放
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案1: Scale 等比例缩放 - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
/* 信息面板 - 不参与缩放 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.85);
color: #fff;
padding: 20px;
border-radius: 8px;
z-index: 9999;
width: 320px;
font-size: 14px;
}
.info-panel h3 {
color: #4fc3f7;
margin-bottom: 12px;
font-size: 16px;
}
.info-panel .pros-cons {
margin-bottom: 15px;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #e57373;
}
.info-panel .current-scale {
background: #ff9800;
color: #000;
padding: 8px 12px;
border-radius: 4px;
font-weight: bold;
margin-top: 10px;
}
/* 大屏容器 - 按 1920*1080 设计 */
.screen-container {
width: 1920px;
height: 1080px;
transform-origin: 0 0;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
position: relative;
overflow: hidden;
}
/* 大屏内容样式 */
.header {
height: 100px;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
color: #fff;
text-shadow: 0 0 20px rgba(79, 195, 247, 0.5);
letter-spacing: 8px;
}
.main-content {
display: flex;
padding: 30px;
gap: 20px;
height: calc(100% - 100px);
}
.sidebar {
width: 400px;
background: rgba(15, 52, 96, 0.3);
border-radius: 16px;
padding: 20px;
border: 1px solid rgba(79, 195, 247, 0.2);
}
.chart-area {
flex: 1;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 16px;
padding: 20px;
border: 1px solid rgba(79, 195, 247, 0.2);
display: flex;
flex-direction: column;
}
.card-title {
color: #4fc3f7;
font-size: 24px;
margin-bottom: 15px;
}
.card-value {
color: #fff;
font-size: 56px;
font-weight: bold;
}
.mini-chart {
flex: 1;
margin-top: 15px;
border-radius: 8px;
min-height: 180px;
}
.notice {
position: absolute;
bottom: 20px;
left: 20px;
right: 20px;
background: rgba(255, 152, 0, 0.2);
border: 1px solid #ff9800;
color: #ff9800;
padding: 15px 20px;
border-radius: 8px;
font-size: 18px;
}
.grid-line {
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
border-top: 2px dashed rgba(79, 195, 247, 0.1);
}
.grid-line::before {
content: '设计稿中心线 (960px)';
position: absolute;
left: 50%;
transform: translateX(-50%);
color: rgba(79, 195, 247, 0.3);
font-size: 14px;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<h3>方案1: Scale 等比例缩放</h3>
<div class="pros-cons">
<div class="pros">✓ 优点:</div>
• 完美还原设计稿比例<br>
• 实现简单直观<br>
• 字体/图表自动缩放<br><br>
<div class="cons">✗ 缺点:</div>
• 屏幕比例不符时出现黑边<br>
• 字体过小可能看不清<br>
• 无法利用多余空间
</div>
<div class="current-scale" id="scaleInfo">
缩放比例: 1.0<br>
窗口尺寸: 1920×1080
</div>
</div>
<!-- 大屏容器 -->
<div class="screen-container" id="screen">
<div class="header">SCALE 方案演示 - 1920×1080 设计稿</div>
<div class="main-content">
<div class="sidebar">
<div class="card-title">左侧信息面板</div>
<p style="color: rgba(255,255,255,0.7); font-size: 18px; line-height: 1.8;">
这是基于 1920×1080 设计稿开发的页面。<br><br>
修改浏览器窗口大小,观察整个页面如何等比例缩放。注意两侧的空白区域(当屏幕比例不是 16:9 时)。
</p>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value" id="value1">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value" id="value2">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value" id="value3">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value" id="value4">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
<div class="grid-line"></div>
<div class="notice">
💡 提示:调整浏览器窗口为 4:3 比例或手机尺寸,观察两侧的黑边/留白。这是 Scale 方案的典型特征。
</div>
</div>
<script>
const screen = document.getElementById('screen');
const scaleInfo = document.getElementById('scaleInfo');
// 设计稿尺寸
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;
function setScale() {
const winW = window.innerWidth;
const winH = window.innerHeight;
// 计算宽高缩放比例,取较小值保持完整显示
const scaleX = winW / DESIGN_WIDTH;
const scaleY = winH / DESIGN_HEIGHT;
const scale = Math.min(scaleX, scaleY);
// 应用缩放
screen.style.transform = `scale(${scale})`;
// 可选:居中显示
const left = (winW - DESIGN_WIDTH * scale) / 2;
const top = (winH - DESIGN_HEIGHT * scale) / 2;
screen.style.position = 'absolute';
screen.style.left = left + 'px';
screen.style.top = top + 'px';
// 更新信息
scaleInfo.innerHTML = `
缩放比例: ${scale.toFixed(3)}<br>
窗口尺寸: ${winW}×${winH}<br>
设计稿: 1920×1080<br>
空白区域: ${Math.round((winW - DESIGN_WIDTH * scale))}×${Math.round((winH - DESIGN_HEIGHT * scale))}
`;
}
setScale();
// ===== ECharts 图表配置 =====
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
chart1.setOption({
backgroundColor: 'transparent',
grid: { top: 30, right: 20, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 12 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff' }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
}
}]
});
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
chart2.setOption({
backgroundColor: 'transparent',
grid: { top: 30, right: 20, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 12 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', formatter: '¥{value}万' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
lineStyle: { color: '#e91e63', width: 3 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
}
}]
});
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
chart3.setOption({
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['40%', '70%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 11 }
}]
});
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
chart4.setOption({
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '80%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 10,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' } },
detail: {
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 20,
offsetCenter: [0, '70%']
},
data: [{ value: 23 }]
}]
});
// 图表引用数组用于resize
const charts = [chart1, chart2, chart3, chart4];
// 防抖处理 resize
let timer;
window.addEventListener('resize', () => {
clearTimeout(timer);
timer = setTimeout(() => {
setScale();
charts.forEach(chart => chart.resize());
}, 100);
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
document.getElementById('value4').textContent = newValue + 'ms';
}, 3000);
</script>
</body>
</html>
使用说明:将以上代码保存为
1-scale-demo.html,直接在浏览器中打开即可体验。调整窗口大小观察等比例缩放效果,注意两侧的黑边。
Demo 2: VW/VH 视口单位方案
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案2: VW/VH 方案 - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
overflow-x: hidden;
}
/* 信息面板 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.85);
color: #fff;
padding: 20px;
border-radius: 8px;
z-index: 9999;
width: 320px;
font-size: 14px;
}
.info-panel h3 {
color: #81c784;
margin-bottom: 12px;
font-size: 16px;
}
.info-panel .pros-cons {
margin-bottom: 15px;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #e57373;
}
.info-panel .formula {
background: #333;
padding: 10px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 12px;
margin-top: 10px;
color: #ff9800;
}
/* VW/VH 布局 - 直接使用视口单位 */
.header {
/* 设计稿 100px / 1080px * 100vh */
height: 9.259vh;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
/* 设计稿 48px / 1080px * 100vh */
font-size: 4.444vh;
color: #fff;
text-shadow: 0 0 2vh rgba(79, 195, 247, 0.5);
letter-spacing: 0.7vw;
}
.main-content {
display: flex;
/* 设计稿 30px / 1080px * 100vh */
padding: 2.778vh 1.562vw;
/* 设计稿 20px / 1080px * 100vh */
gap: 1.852vh 1.042vw;
/* 总高度 100vh - header 高度 */
height: 90.741vh;
}
.sidebar {
/* 设计稿 400px / 1920px * 100vw */
width: 20.833vw;
background: rgba(15, 52, 96, 0.3);
/* 设计稿 16px / 1080px * 100vh */
border-radius: 1.481vh;
/* 设计稿 20px / 1080px * 100vh */
padding: 1.852vh;
border: 0.093vh solid rgba(79, 195, 247, 0.2);
}
.chart-area {
flex: 1;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1.852vh 1.042vw;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 1.481vh;
padding: 1.852vh;
border: 0.093vh solid rgba(79, 195, 247, 0.2);
display: flex;
flex-direction: column;
}
.card-title {
color: #4fc3f7;
/* 设计稿 24px / 1080px * 100vh */
font-size: 2.222vh;
margin-bottom: 1.389vh;
}
.card-value {
color: #fff;
/* 设计稿 56px / 1080px * 100vh */
font-size: 5.185vh;
font-weight: bold;
}
.mini-chart {
flex: 1;
min-height: 13.889vh;
margin-top: 1.5vh;
border-radius: 0.741vh;
}
/* 代码展示区域 */
.code-panel {
margin-top: 2vh;
background: rgba(0, 0, 0, 0.5);
padding: 1.5vh;
border-radius: 1vh;
font-family: 'Courier New', monospace;
font-size: 1.3vh;
color: #a5d6a7;
overflow: hidden;
}
.notice {
position: fixed;
bottom: 2vh;
left: 2vw;
right: 22vw;
background: rgba(244, 67, 54, 0.2);
border: 1px solid #f44336;
color: #f44336;
padding: 1.5vh 2vw;
border-radius: 0.8vh;
font-size: 1.6vh;
}
/* 问题演示:文字溢出 */
.overflow-demo {
background: rgba(244, 67, 54, 0.1);
border: 1px dashed #f44336;
padding: 1vh;
margin-top: 1vh;
font-size: 1.5vh;
}
/* 使用 CSS 变量简化计算 */
:root {
--vh: 1vh;
--vw: 1vw;
}
/* 但这不是完美的解决方案 */
.sidebar p {
color: rgba(255,255,255,0.7);
font-size: 1.667vh;
line-height: 1.8;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<h3>方案2: VW/VH 方案</h3>
<div class="pros-cons">
<div class="pros">✓ 优点:</div>
• 无 JS 依赖<br>
• 利用全部视口空间<br>
• 无黑边/留白<br><br>
<div class="cons">✗ 缺点:</div>
• 计算公式复杂<br>
• 单位换算容易出错<br>
• 字体可能过大/过小<br>
• 宽高比例难以协调
</div>
<div class="formula">
计算公式:<br>
100px / 1920px * 100vw<br>
= 5.208vw
</div>
</div>
<!-- 页面内容 -->
<div class="header">VW/VH 方案演示 - 满屏无黑边</div>
<div class="main-content">
<div class="sidebar">
<div class="card-title">左侧信息面板</div>
<p>
此方案使用 vw/vh 单位代替 px。<br><br>
虽然页面始终铺满屏幕,但计算复杂。注意右侧卡牌区域在小屏幕上文字可能显得过大。
</p>
<div class="code-panel">
/* 实际开发中的混乱 */<br>
width: 20.833vw;<br>
height: 13.889vh;<br>
font-size: 4.444vh;<br>
padding: 1.852vh 1.562vw;<br>
/* 这些数字是怎么来的? */
</div>
<div class="overflow-demo">
<strong>⚠️ 问题演示:</strong><br>
当屏幕很宽但很矮时,文字按 vh 计算变得极小,而容器按 vw 计算保持宽大,导致内容稀疏。
</div>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
<div class="notice">
⚠️ 缺点演示:调整浏览器窗口为超宽矮屏(如 2560×600),观察字体与容器比例的失调。对比 Scale 方案在这个场景的表现。
</div>
<script>
// ===== ECharts 图表配置 =====
// 图表1: 柱状图 - 实时用户数
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
const option1 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 45 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
},
animationDuration: 1500
}]
};
chart1.setOption(option1);
// 图表2: 折线图 - 交易金额趋势
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
const option2 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10, formatter: '¥{value}' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
symbol: 'circle',
symbolSize: 6,
lineStyle: { color: '#e91e63', width: 3 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
},
animationDuration: 1500
}]
};
chart2.setOption(option2);
// 图表3: 饼图 - 系统负载分布
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
const option3 = {
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['35%', '65%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 10 },
labelLine: { lineStyle: { color: 'rgba(255,255,255,0.5)' } },
animationDuration: 1500
}]
};
chart3.setOption(option3);
// 图表4: 仪表盘 - 响应时间
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
const option4 = {
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '75%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 8,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' }, width: 4 },
axisTick: { distance: -8, length: 4, lineStyle: { color: '#fff' } },
splitLine: { distance: -8, length: 10, lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff', distance: -20, fontSize: 9 },
detail: {
valueAnimation: true,
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 16,
offsetCenter: [0, '65%']
},
data: [{ value: 23 }],
animationDuration: 2000
}]
};
chart4.setOption(option4);
// 响应式调整
const charts = [chart1, chart2, chart3, chart4];
window.addEventListener('resize', () => {
charts.forEach(chart => chart.resize());
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
}, 3000);
</script>
</body>
</html>
Demo 3: Rem 动态计算方案
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案3: Rem 方案 - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
// Rem 计算逻辑
(function() {
const designWidth = 1920;
function setRem() {
const winWidth = window.innerWidth;
// 以设计稿宽度为基准,100rem = 设计稿宽度
const rem = winWidth / designWidth * 100;
document.documentElement.style.fontSize = rem + 'px';
}
setRem();
let timer;
window.addEventListener('resize', function() {
clearTimeout(timer);
timer = setTimeout(setRem, 100);
});
})();
</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
overflow-x: hidden;
}
/* 信息面板 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.85);
color: #fff;
padding: 0.2rem;
border-radius: 0.08rem;
z-index: 9999;
width: 3.3rem;
font-size: 0.073rem;
}
.info-panel h3 {
color: #4fc3f7;
margin-bottom: 0.062rem;
font-size: 0.083rem;
}
.info-panel .pros-cons {
margin-bottom: 0.078rem;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #e57373;
}
.info-panel .current-rem {
background: #4caf50;
color: #000;
padding: 0.05rem;
border-radius: 0.04rem;
font-weight: bold;
margin-top: 0.05rem;
}
/* Rem 布局 - 1rem = 设计稿中 100px (在 1920px 宽度下) */
.header {
/* 设计稿 100px = 1rem */
height: 1rem;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
/* 设计稿 48px = 0.48rem */
font-size: 0.48rem;
color: #fff;
text-shadow: 0 0 0.1rem rgba(79, 195, 247, 0.5);
letter-spacing: 0.08rem;
}
.main-content {
display: flex;
/* 设计稿 30px = 0.3rem */
padding: 0.3rem;
/* 设计稿 20px = 0.2rem */
gap: 0.2rem;
/* 总高度 100vh - header */
min-height: calc(100vh - 1rem);
}
.sidebar {
/* 设计稿 400px = 4rem */
width: 4rem;
background: rgba(15, 52, 96, 0.3);
/* 设计稿 16px = 0.16rem */
border-radius: 0.16rem;
padding: 0.2rem;
border: 0.01rem solid rgba(79, 195, 247, 0.2);
}
.sidebar p {
color: rgba(255,255,255,0.7);
font-size: 0.18rem;
line-height: 1.8;
}
.chart-area {
flex: 1;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.2rem;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 0.16rem;
padding: 0.2rem;
border: 0.01rem solid rgba(79, 195, 247, 0.2);
display: flex;
flex-direction: column;
}
.card-title {
color: #4fc3f7;
font-size: 0.22rem;
margin-bottom: 0.12rem;
}
.card-value {
color: #fff;
font-size: 0.56rem;
font-weight: bold;
}
.mini-chart {
flex: 1;
min-height: 1.5rem;
margin-top: 0.15rem;
border-radius: 0.08rem;
}
/* 代码展示 */
.code-panel {
margin-top: 0.25rem;
background: rgba(0, 0, 0, 0.5);
padding: 0.15rem;
border-radius: 0.1rem;
font-family: 'Courier New', monospace;
font-size: 0.13rem;
color: #a5d6a7;
}
/* 闪烁问题演示 */
.flash-demo {
margin-top: 0.2rem;
padding: 0.15rem;
background: rgba(255, 152, 0, 0.1);
border: 1px dashed #ff9800;
color: #ff9800;
font-size: 0.15rem;
}
.fouc-warning {
background: rgba(244, 67, 54, 0.2);
border: 1px solid #f44336;
color: #f44336;
padding: 0.15rem;
margin-top: 0.2rem;
border-radius: 0.08rem;
font-size: 0.15rem;
}
.notice {
position: fixed;
bottom: 0.2rem;
left: 0.3rem;
right: 3.6rem;
background: rgba(255, 152, 0, 0.2);
border: 1px solid #ff9800;
color: #ff9800;
padding: 0.15rem 0.2rem;
border-radius: 0.08rem;
font-size: 0.16rem;
}
/* FOUC 模拟 - 页面加载时的闪烁 */
.no-js-fallback {
display: none;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<h3>方案3: Rem 方案</h3>
<div class="pros-cons">
<div class="pros">✓ 优点:</div>
• 计算相对直观 (设计稿/100)<br>
• 兼容性好 (支持 IE)<br>
• 宽高等比缩放<br><br>
<div class="cons">✗ 缺点:</div>
• 依赖 JS 设置根字体<br>
• 页面加载可能闪烁<br>
• 高度仍需要特殊处理<br>
• 设计稿转换工作量大
</div>
<div class="current-rem" id="remInfo">
根字体: 100px<br>
(1920px 宽度下)
</div>
</div>
<!-- 页面内容 -->
<div class="header">REM 方案演示 - JS 动态计算</div>
<div class="main-content">
<div class="sidebar">
<div class="card-title">左侧信息面板</div>
<p>
1rem = 设计稿的 100px<br><br>
在 1920px 宽度的屏幕上,根字体大小为 100px,便于计算转换。
</p>
<div class="code-panel">
// JS 计算根字体 (head 中)<br>
const rem = winWidth / 1920 * 100;<br>
html.style.fontSize = rem + 'px';<br><br>
// CSS 使用<br>
width: 4rem; /* = 400px */
</div>
<div class="flash-demo">
<strong>⚠️ 闪烁问题 (FOUC):</strong><br>
如果 JS 在 head 末尾执行,页面会先按默认 16px 渲染,然后跳动到计算值。
</div>
<div class="fouc-warning">
💡 解决方案:将 rem 计算脚本放在 <head> 最前面,或使用内联 style。
</div>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
<div class="notice">
💡 修改窗口大小观察变化。注意:此方案主要处理宽度适配,高度方向元素可能会超出屏幕(尝试将窗口压得很矮)。
</div>
<script>
// 更新 rem 信息
function updateRemInfo() {
const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
document.getElementById('remInfo').innerHTML = `
根字体: ${rem.toFixed(2)}px<br>
窗口宽度: ${window.innerWidth}px<br>
1rem = 设计稿的 100px
`;
}
updateRemInfo();
let timer;
window.addEventListener('resize', function() {
clearTimeout(timer);
timer = setTimeout(updateRemInfo, 100);
});
// ===== ECharts 图表配置 =====
// 图表1: 柱状图 - 实时用户数
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
const option1 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 45 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
},
animationDuration: 1500
}]
};
chart1.setOption(option1);
// 图表2: 折线图 - 交易金额趋势
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
const option2 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10, formatter: '¥{value}' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
symbol: 'circle',
symbolSize: 6,
lineStyle: { color: '#e91e63', width: 3 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
},
animationDuration: 1500
}]
};
chart2.setOption(option2);
// 图表3: 饼图 - 系统负载分布
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
const option3 = {
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['35%', '65%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 10 },
labelLine: { lineStyle: { color: 'rgba(255,255,255,0.5)' } },
animationDuration: 1500
}]
};
chart3.setOption(option3);
// 图表4: 仪表盘 - 响应时间
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
const option4 = {
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '75%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 8,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' }, width: 4 },
axisTick: { distance: -8, length: 4, lineStyle: { color: '#fff' } },
splitLine: { distance: -8, length: 10, lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff', distance: -20, fontSize: 9 },
detail: {
valueAnimation: true,
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 16,
offsetCenter: [0, '65%']
},
data: [{ value: 23 }],
animationDuration: 2000
}]
};
chart4.setOption(option4);
// 响应式调整
const charts = [chart1, chart2, chart3, chart4];
window.addEventListener('resize', () => {
charts.forEach(chart => chart.resize());
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
}, 3000);
</script>
</body>
</html>
Demo 4: 流式/弹性布局方案
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案4: 流式布局 - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
overflow-x: hidden;
}
/* 信息面板 - 使用 px 保持固定大小参考 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.85);
color: #fff;
padding: 20px;
border-radius: 8px;
z-index: 9999;
width: 320px;
font-size: 14px;
}
.info-panel h3 {
color: #ff9800;
margin-bottom: 12px;
font-size: 16px;
}
.info-panel .pros-cons {
margin-bottom: 15px;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #e57373;
}
/* 流式布局 - 使用 % fr auto 等弹性单位 */
.header {
height: 10%; /* 百分比高度 */
min-height: 60px;
max-height: 120px;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
font-size: clamp(24px, 4vw, 48px); /* 流体字体 */
color: #fff;
text-shadow: 0 0 20px rgba(79, 195, 247, 0.5);
letter-spacing: 0.5vw;
padding: 0 5%;
}
.main-content {
display: flex;
padding: 3%;
gap: 2%;
min-height: calc(90% - 60px);
}
.sidebar {
width: 25%; /* 百分比宽度 */
min-width: 200px;
max-width: 400px;
background: rgba(15, 52, 96, 0.3);
border-radius: 16px;
padding: 20px;
border: 1px solid rgba(79, 195, 247, 0.2);
}
.sidebar p {
color: rgba(255,255,255,0.7);
font-size: clamp(14px, 1.5vw, 18px);
line-height: 1.8;
}
/* CSS Grid 布局 */
.chart-area {
flex: 1;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 16px;
padding: 20px;
border: 1px solid rgba(79, 195, 247, 0.2);
display: flex;
flex-direction: column;
min-height: 150px;
}
.card-title {
color: #4fc3f7;
font-size: clamp(16px, 2vw, 24px);
margin-bottom: 10px;
}
.card-value {
color: #fff;
font-size: clamp(28px, 4vw, 56px);
font-weight: bold;
white-space: nowrap;
}
.mini-chart {
flex: 1;
min-height: 100px;
margin-top: 10px;
border-radius: 8px;
}
/* 问题展示:数据大屏布局崩坏 */
.problem-demo {
margin-top: 20px;
padding: 15px;
background: rgba(244, 67, 54, 0.1);
border: 1px dashed #f44336;
border-radius: 8px;
}
.problem-demo h4 {
color: #f44336;
margin-bottom: 10px;
}
.problem-demo p {
color: #f44336;
font-size: 14px;
}
/* 视觉偏差对比: */
.comparison-box {
display: flex;
gap: 20px;
margin-top: 15px;
}
.fixed-ratio {
width: 100px;
height: 60px;
background: #4fc3f7;
display: flex;
align-items: center;
justify-content: center;
color: #000;
font-size: 12px;
}
.fluid-shape {
width: 20%;
padding-bottom: 12%;
background: #ff9800;
position: relative;
}
.fluid-shape span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #000;
font-size: 12px;
white-space: nowrap;
}
.notice {
position: fixed;
bottom: 20px;
left: 20px;
right: 360px;
background: rgba(244, 67, 54, 0.2);
border: 1px solid #f44336;
color: #f44336;
padding: 15px 20px;
border-radius: 8px;
font-size: 14px;
}
.label-tag {
display: inline-block;
background: #4caf50;
color: #fff;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
margin-right: 5px;
}
.label-tag.warning {
background: #ff9800;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<h3>方案4: 流式/弹性布局</h3>
<div class="pros-cons">
<div class="pros">✓ 优点:</div>
• 纯 CSS,无依赖<br>
• 自然响应式<br>
• 内容自适应<br><br>
<div class="cons">✗ 缺点:</div>
• <strong>大屏空间利用率低</strong><br>
• 图表比例难以控制<br>
• 无法精确还原设计稿<br>
• 文字/图形可能变形
</div>
<div style="margin-top: 10px; font-size: 12px; color: #999;">
适合:后台管理系统<br>
不适合:数据可视化大屏
</div>
</div>
<!-- 页面内容 -->
<div class="header">流式布局演示 - 自然伸缩</div>
<div class="main-content">
<div class="sidebar">
<div style="color: #ff9800; font-size: 18px; margin-bottom: 15px;">左侧信息面板</div>
<p>
<span class="label-tag">%</span> 百分比宽度<br>
<span class="label-tag">fr</span> Grid 弹性分配<br>
<span class="label-tag warning">clamp</span> 流体字体<br><br>
这个方案使用 CSS 的固有响应式能力。但请注意右侧卡片在宽屏上的变化——它们会无限拉宽!
</p>
<div class="problem-demo">
<h4>⚠️ 大屏场景的问题</h4>
<p>
<strong>问题1:</strong> 宽屏下卡片过度拉伸<br>
<strong>问题2:</strong> 图表比例失控<br>
<strong>问题3:</strong> 无法精确对齐设计稿像素
</p>
<div class="comparison-box">
<div class="fixed-ratio">固定比例</div>
<div class="fluid-shape"><span>20%宽度</span></div>
</div>
<p style="margin-top: 10px; font-size: 12px;">
调整窗口宽度,观察流体元素的宽高比例变化。
</p>
</div>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
<div class="notice">
❌ 调整窗口到超宽屏(≥2560px),观察右侧卡片的变形:宽高比例完全失控,图表变成"矮胖"形状。对比 Scale 方案在这个场景的表现。
</div>
<script>
// ===== ECharts 图表配置 =====
// 图表1: 柱状图 - 实时用户数
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
const option1 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 45 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
},
animationDuration: 1500
}]
};
chart1.setOption(option1);
// 图表2: 折线图 - 交易金额趋势
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
const option2 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10, formatter: '¥{value}' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
symbol: 'circle',
symbolSize: 6,
lineStyle: { color: '#e91e63', width: 3 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
},
animationDuration: 1500
}]
};
chart2.setOption(option2);
// 图表3: 饼图 - 系统负载分布
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
const option3 = {
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['35%', '65%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 10 },
labelLine: { lineStyle: { color: 'rgba(255,255,255,0.5)' } },
animationDuration: 1500
}]
};
chart3.setOption(option3);
// 图表4: 仪表盘 - 响应时间
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
const option4 = {
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '75%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 8,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' }, width: 4 },
axisTick: { distance: -8, length: 4, lineStyle: { color: '#fff' } },
splitLine: { distance: -8, length: 10, lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff', distance: -20, fontSize: 9 },
detail: {
valueAnimation: true,
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 16,
offsetCenter: [0, '65%']
},
data: [{ value: 23 }],
animationDuration: 2000
}]
};
chart4.setOption(option4);
// 响应式调整
const charts = [chart1, chart2, chart3, chart4];
window.addEventListener('resize', () => {
charts.forEach(chart => chart.resize());
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
}, 3000);
</script>
</body>
</html>
Demo 5: 响应式断点方案
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案5: 响应式断点 - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
overflow-x: hidden;
}
/* 信息面板 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.85);
color: #fff;
padding: 20px;
border-radius: 8px;
z-index: 9999;
width: 320px;
font-size: 14px;
max-height: 90vh;
overflow-y: auto;
}
.info-panel h3 {
color: #e91e63;
margin-bottom: 12px;
font-size: 16px;
}
.info-panel .pros-cons {
margin-bottom: 15px;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #e57373;
}
.current-breakpoint {
background: #e91e63;
color: #fff;
padding: 10px;
border-radius: 4px;
font-weight: bold;
margin-top: 10px;
font-size: 16px;
}
.breakpoint-list {
margin-top: 10px;
font-size: 12px;
}
.breakpoint-list div {
padding: 4px 0;
}
.breakpoint-list .active {
color: #e91e63;
font-weight: bold;
}
/* 断点样式定义 */
/* 默认/移动端: < 768px */
.header {
height: 50px;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
color: #fff;
text-shadow: 0 0 10px rgba(79, 195, 247, 0.5);
letter-spacing: 2px;
}
.main-content {
display: flex;
flex-direction: column;
padding: 10px;
gap: 15px;
}
.sidebar {
width: 100%;
background: rgba(15, 52, 96, 0.3);
border-radius: 8px;
padding: 15px;
border: 1px solid rgba(79, 195, 247, 0.2);
}
.sidebar p {
color: rgba(255,255,255,0.7);
font-size: 14px;
line-height: 1.6;
}
.chart-area {
display: grid;
grid-template-columns: 1fr;
gap: 15px;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 8px;
padding: 15px;
border: 1px solid rgba(79, 195, 247, 0.2);
}
.card-title {
color: #4fc3f7;
font-size: 16px;
margin-bottom: 8px;
}
.card-value {
color: #fff;
font-size: 28px;
font-weight: bold;
}
.mini-chart {
height: 100px;
margin-top: 10px;
border-radius: 4px;
}
/* 平板: 768px - 1200px */
@media (min-width: 768px) {
.header {
height: 70px;
font-size: 24px;
letter-spacing: 4px;
}
.main-content {
flex-direction: row;
padding: 20px;
}
.sidebar {
width: 280px;
padding: 20px;
}
.chart-area {
grid-template-columns: repeat(2, 1fr);
flex: 1;
}
.card-title {
font-size: 18px;
}
.card-value {
font-size: 32px;
}
.mini-chart {
height: 100px;
}
}
/* 代码体积问题展示 */
@media (min-width: 1200px) {
.header {
height: 80px;
font-size: 32px;
letter-spacing: 6px;
}
.main-content {
padding: 25px;
gap: 20px;
}
.sidebar {
width: 350px;
}
.card-title {
font-size: 20px;
margin-bottom: 10px;
}
.card-value {
font-size: 40px;
}
.mini-chart {
height: 120px;
margin-top: 15px;
}
}
/* 大屏幕: 1920px - 2560px */
@media (min-width: 1920px) {
.header {
height: 100px;
font-size: 40px;
letter-spacing: 8px;
}
.main-content {
padding: 30px;
}
.sidebar {
width: 400px;
}
.sidebar p {
font-size: 16px;
}
.card-value {
font-size: 48px;
}
.mini-chart {
height: 150px;
}
}
/* 超大屏幕: > 2560px */
@media (min-width: 2560px) {
.header {
height: 120px;
font-size: 48px;
}
.chart-area {
grid-template-columns: repeat(4, 1fr);
}
.card-value {
font-size: 56px;
}
}
/* 代码体积问题展示 */
.code-stats {
margin-top: 15px;
padding: 10px;
background: rgba(244, 67, 54, 0.1);
border: 1px dashed #f44336;
border-radius: 4px;
}
.code-stats h4 {
color: #f44336;
margin-bottom: 5px;
}
.code-stats .stat {
display: flex;
justify-content: space-between;
font-size: 12px;
padding: 3px 0;
}
.notice {
position: fixed;
bottom: 20px;
left: 20px;
right: 360px;
background: rgba(233, 30, 99, 0.2);
border: 1px solid #e91e63;
color: #e91e63;
padding: 15px 20px;
border-radius: 8px;
font-size: 14px;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<h3>方案5: 响应式断点</h3>
<div class="pros-cons">
<div class="pros">✓ 优点:</div>
• 精确控制各分辨率<br>
• 字体可读性可控<br>
• 适合固定规格大屏<br><br>
<div class="cons">✗ 缺点:</div>
• <strong>代码量爆炸</strong><br>
• 维护困难<br>
• 无法覆盖所有尺寸<br>
• CSS 文件体积大
</div>
<div class="current-breakpoint" id="currentBP">
当前断点: 默认/移动端
</div>
<div class="breakpoint-list">
<div data-bp="0">< 768px: 移动端</div>
<div data-bp="1">768px - 1200px: 平板</div>
<div data-bp="2">1200px - 1920px: 桌面</div>
<div data-bp="3">1920px - 2560px: 大屏</div>
<div data-bp="4">> 2560px: 超大屏</div>
</div>
<div class="code-stats">
<h4>⚠️ 维护成本</h4>
<div class="stat">
<span>每个组件</span>
<span>×5 套样式</span>
</div>
<div class="stat">
<span>10个组件</span>
<span>= 50套样式</span>
</div>
<div class="stat">
<span>新增分辨率</span>
<span>全文件修改</span>
</div>
</div>
</div>
<!-- 页面内容 -->
<div class="header">响应式断点演示 - @media 查询</div>
<div class="main-content">
<div class="sidebar">
<div style="color: #e91e63; font-size: 20px; margin-bottom: 15px;">左侧信息面板</div>
<p>
调整窗口宽度,观察布局在不同断点的变化。<br><br>
<strong>可能遇到的问题:</strong><br>
• 1366px 和 1440px 怎么办?<br>
• 3840px(4K)应该如何显示?<br>
• 修改一个组件要改 5 处?
</p>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
<div class="notice">
🔧 拖动窗口宽度观察布局变化。注意:即使 "桌面" 断点(1920px)也不是精确还原设计稿,只是 "看起来差不多"。
</div>
<script>
// 检测当前断点
const breakpoints = [
{ name: '默认/移动端', max: 768 },
{ name: '平板', max: 1200 },
{ name: '桌面', max: 1920 },
{ name: '大屏', max: 2560 },
{ name: '超大屏', max: Infinity }
];
function detectBreakpoint() {
const width = window.innerWidth;
let activeIndex = 0;
for (let i = 0; i < breakpoints.length; i++) {
if (width < breakpoints[i].max) {
activeIndex = i;
break;
}
activeIndex = i;
}
document.getElementById('currentBP').textContent =
`当前断点: ${breakpoints[activeIndex].name} (${width}px)`;
// 高亮断点列表
document.querySelectorAll('.breakpoint-list div').forEach((div, index) => {
div.classList.toggle('active', index === activeIndex);
});
}
detectBreakpoint();
let timer;
window.addEventListener('resize', () => {
clearTimeout(timer);
timer = setTimeout(detectBreakpoint, 100);
});
// ===== ECharts 图表配置 =====
// 图表1: 柱状图 - 实时用户数
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
const option1 = {
backgroundColor: 'transparent',
grid: { top: 25, right: 10, bottom: 20, left: 40 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 9 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 9 }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
},
animationDuration: 1500
}]
};
chart1.setOption(option1);
// 图表2: 折线图 - 交易金额趋势
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
const option2 = {
backgroundColor: 'transparent',
grid: { top: 25, right: 10, bottom: 20, left: 45 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 9 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 9, formatter: '¥{value}' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
symbol: 'circle',
symbolSize: 5,
lineStyle: { color: '#e91e63', width: 2 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
},
animationDuration: 1500
}]
};
chart2.setOption(option2);
// 图表3: 饼图 - 系统负载分布
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
const option3 = {
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['30%', '60%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 9 },
labelLine: { lineStyle: { color: 'rgba(255,255,255,0.5)' } },
animationDuration: 1500
}]
};
chart3.setOption(option3);
// 图表4: 仪表盘 - 响应时间
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
const option4 = {
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '70%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 6,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' }, width: 3 },
axisTick: { distance: -6, length: 3, lineStyle: { color: '#fff' } },
splitLine: { distance: -6, length: 8, lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff', distance: -15, fontSize: 8 },
detail: {
valueAnimation: true,
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 12,
offsetCenter: [0, '60%']
},
data: [{ value: 23 }],
animationDuration: 2000
}]
};
chart4.setOption(option4);
// 响应式调整
const charts = [chart1, chart2, chart3, chart4];
window.addEventListener('resize', () => {
charts.forEach(chart => chart.resize());
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
}, 3000);
</script>
</body>
</html>
Demo 6: 混合方案(推荐)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方案6: 混合方案(推荐) - 大屏适配方案对比</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
// 混合方案:Scale + Rem
(function() {
const designWidth = 1920;
const designHeight = 1080;
const minScale = 0.6; // 最小缩放限制,防止过小
function adapt() {
const winW = window.innerWidth;
const winH = window.innerHeight;
// Scale 计算
const scaleX = winW / designWidth;
const scaleY = winH / designHeight;
const scale = Math.max(Math.min(scaleX, scaleY), minScale);
// 应用 scale
const screen = document.getElementById('screen');
if (screen) {
screen.style.transform = `scale(${scale})`;
}
// Rem 计算 - 根据缩放比例调整根字体
// 当 scale < 1 时,增加根字体补偿
const baseRem = 100;
const fontScale = Math.max(scale, minScale);
const rem = baseRem * fontScale;
document.documentElement.style.fontSize = rem + 'px';
// 更新信息面板
updateInfo(scale, rem, winW, winH);
}
function updateInfo(scale, rem, winW, winH) {
const info = document.getElementById('mixedInfo');
if (info) {
info.innerHTML = `
Scale: ${scale.toFixed(3)}<br>
Rem: ${rem.toFixed(1)}px<br>
窗口: ${winW}×${winH}<br>
最小限制: ${minScale}
`;
}
}
// 页面加载前执行
adapt();
// 防抖 resize
let timer;
window.addEventListener('resize', () => {
clearTimeout(timer);
timer = setTimeout(adapt, 100);
});
// 暴露全局供切换模式使用
window.adaptMode = 'mixed'; // mixed, scale-only, rem-only
window.setAdaptMode = function(mode) {
window.adaptMode = mode;
const screen = document.getElementById('screen');
const designWidth = 1920;
const designHeight = 1080;
const winW = window.innerWidth;
const winH = window.innerHeight;
if (mode === 'scale-only') {
const scale = Math.min(winW / designWidth, winH / designHeight);
screen.style.transform = `scale(${scale})`;
document.documentElement.style.fontSize = '100px';
} else if (mode === 'rem-only') {
screen.style.transform = 'none';
const rem = winW / designWidth * 100;
document.documentElement.style.fontSize = rem + 'px';
} else {
adapt();
}
};
// 初始化覆盖
window.setAdaptMode('mixed');
})();
</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
overflow: hidden;
background: #0a0a1a;
}
/* 信息面板 - 固定不缩放 */
.info-panel {
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.9);
color: #fff;
padding: 20px;
border-radius: 8px;
z-index: 9999;
width: 340px;
font-size: 14px;
border: 1px solid #4caf50;
}
.info-panel h3 {
color: #4caf50;
margin-bottom: 12px;
font-size: 16px;
}
.info-panel .recommend {
background: #4caf50;
color: #000;
padding: 5px 10px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
display: inline-block;
margin-bottom: 10px;
}
.info-panel .pros-cons {
margin-bottom: 15px;
}
.info-panel .pros {
color: #81c784;
}
.info-panel .cons {
color: #fff176;
}
.mode-switcher {
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid #333;
}
.mode-switcher h4 {
color: #4fc3f7;
margin-bottom: 10px;
}
.mode-btn {
display: block;
width: 100%;
padding: 8px 12px;
margin-bottom: 6px;
background: #333;
color: #fff;
border: 1px solid #555;
border-radius: 4px;
cursor: pointer;
text-align: left;
font-size: 12px;
}
.mode-btn:hover {
background: #444;
}
.mode-btn.active {
background: #4caf50;
border-color: #4caf50;
color: #000;
}
.info-value {
background: #2196f3;
color: #fff;
padding: 10px;
border-radius: 4px;
margin-top: 10px;
font-family: 'Courier New', monospace;
font-size: 12px;
}
/* 大屏容器 */
.screen-container {
width: 1920px;
height: 1080px;
transform-origin: 0 0;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
position: absolute;
overflow: hidden;
top: 0;
left: 0;
}
/* 居中显示 */
.centered {
transition: transform 0.3s ease, left 0.3s ease, top 0.3s ease;
}
/* 大屏内容样式 - 使用 rem */
.header {
height: 1rem;
background: linear-gradient(90deg, #0f3460 0%, #533483 50%, #0f3460 100%);
display: flex;
align-items: center;
justify-content: center;
font-size: 0.5rem;
color: #fff;
text-shadow: 0 0 0.1rem rgba(79, 195, 247, 0.5);
letter-spacing: 0.08rem;
}
.main-content {
display: flex;
padding: 0.3rem;
gap: 0.2rem;
height: calc(100% - 1rem);
}
.sidebar {
width: 4rem;
background: rgba(15, 52, 96, 0.3);
border-radius: 0.16rem;
padding: 0.2rem;
border: 0.01rem solid rgba(79, 195, 247, 0.2);
}
.sidebar p {
color: rgba(255,255,255,0.7);
font-size: 0.18rem;
line-height: 1.8;
}
.chart-area {
flex: 1;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.2rem;
}
.card {
background: rgba(15, 52, 96, 0.3);
border-radius: 0.16rem;
padding: 0.2rem;
border: 0.01rem solid rgba(79, 195, 247, 0.2);
display: flex;
flex-direction: column;
}
.card-title {
color: #4fc3f7;
font-size: 0.22rem;
margin-bottom: 0.08rem;
}
.card-value {
color: #fff;
font-size: 0.56rem;
font-weight: bold;
}
.mini-chart {
flex: 1;
min-height: 1.5rem;
margin-top: 0.15rem;
border-radius: 0.08rem;
}
/* 特性说明卡片 */
.feature-card {
margin-top: 0.15rem;
padding: 0.15rem;
background: rgba(76, 175, 80, 0.1);
border: 1px solid #4caf50;
border-radius: 0.1rem;
}
.feature-card h4 {
color: #4caf50;
font-size: 0.18rem;
margin-bottom: 0.05rem;
}
.feature-card p {
font-size: 0.14rem;
color: rgba(255,255,255,0.8);
}
/* 对比指示器 */
.compare-indicator {
position: fixed;
bottom: 20px;
left: 20px;
background: rgba(0, 0, 0, 0.9);
padding: 15px 20px;
border-radius: 8px;
color: #fff;
border-left: 4px solid #4caf50;
}
.compare-indicator h4 {
color: #4caf50;
margin-bottom: 5px;
}
</style>
</head>
<body>
<!-- 信息面板 -->
<div class="info-panel">
<div class="recommend">⭐ 生产环境推荐</div>
<h3>方案6: 混合方案</h3>
<div class="pros-cons">
<div class="pros">✓ 结合 Scale + Rem 优点</div>
• 等比例缩放保证布局<br>
• 字体最小值防止过小<br>
• 大屏清晰、小屏可读<br><br>
<div class="cons">△ 注意:</div>
• 需要 JS 支持<br>
• 计算逻辑稍复杂
</div>
<div class="mode-switcher">
<h4>模式切换对比:</h4>
<button class="mode-btn active" onclick="switchMode('mixed', this)">
🌟 混合方案 (推荐)
</button>
<button class="mode-btn" onclick="switchMode('scale-only', this)">
📐 纯 Scale (字体过小)
</button>
<button class="mode-btn" onclick="switchMode('rem-only', this)">
🔤 纯 Rem (可能变形)
</button>
</div>
<div class="info-value" id="mixedInfo">
Scale: 1.0<br>
Rem: 100px<br>
窗口: 1920×1080
</div>
</div>
<!-- 对比指示器 -->
<div class="compare-indicator">
<h4>💡 对比技巧</h4>
<p>1. 切换到"纯 Scale",缩小窗口,观察字体变小</p>
<p>2. 切换回"混合方案",字体有最小值限制</p>
<p>3. 调整到4K屏,观察布局比例保持与设计稿一致</p>
</div>
<!-- 大屏容器 -->
<div class="screen-container centered" id="screen">
<div class="header">混合方案演示 - Scale + Rem 双重保障</div>
<div class="main-content">
<div class="sidebar">
<div style="color: #4caf50; font-size: 0.24rem; margin-bottom: 0.15rem;">混合方案说明</div>
<p>
此方案结合 Scale 的视觉一致性 和 Rem 的灵活性。<br><br>
<strong>核心算法:</strong><br>
1. 计算 screen 的 scale 比例<br>
2. 根字体 = baseFont * max(scale, minLimit)<br>
3. 所有尺寸使用 rem 单位<br><br>
这样既保持设计稿比例,又确保文字可读。
</p>
<div class="feature-card">
<h4>🎯 最小字体保护</h4>
<p>当屏幕缩小时,字体不会无限缩小,保证基本可读性。</p>
</div>
<div class="feature-card">
<h4>📐 严格比例保持</h4>
<p>图表、卡片的宽高比例严格遵循设计稿,无变形。</p>
</div>
</div>
<div class="chart-area">
<div class="card">
<div class="card-title">实时用户数</div>
<div class="card-value">128,456</div>
<div class="mini-chart" id="chart1"></div>
</div>
<div class="card">
<div class="card-title">交易金额</div>
<div class="card-value">¥2.3M</div>
<div class="mini-chart" id="chart2"></div>
</div>
<div class="card">
<div class="card-title">系统负载</div>
<div class="card-value">68%</div>
<div class="mini-chart" id="chart3"></div>
</div>
<div class="card">
<div class="card-title">响应时间</div>
<div class="card-value">23ms</div>
<div class="mini-chart" id="chart4"></div>
</div>
</div>
</div>
</div>
<script>
function switchMode(mode, btn) {
window.setAdaptMode(mode);
// 更新按钮状态
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
// 更新位置信息
updatePosition();
}
function updatePosition() {
const screen = document.getElementById('screen');
const winW = window.innerWidth;
const winH = window.innerHeight;
const designW = 1920;
const designH = 1080;
// 获取当前 scale
const transform = getComputedStyle(screen).transform;
let scale = 1;
if (transform && transform !== 'none') {
const matrix = transform.match(/matrix\(([^)]+)\)/);
if (matrix) {
const values = matrix[1].split(',').map(parseFloat);
scale = values[0];
}
}
// 居中计算
const left = (winW - designW * scale) / 2;
const top = (winH - designH * scale) / 2;
screen.style.left = Math.max(0, left) + 'px';
screen.style.top = Math.max(0, top) + 'px';
}
// 初始化位置
window.addEventListener('load', updatePosition);
window.addEventListener('resize', updatePosition);
// ===== ECharts 图表配置 =====
// 图表1: 柱状图 - 实时用户数
const chart1 = echarts.init(document.getElementById('chart1'), 'dark');
const option1 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 45 },
xAxis: {
type: 'category',
data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
axisLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(79, 195, 247, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
series: [{
type: 'bar',
data: [32000, 28000, 85000, 120000, 98000, 128456],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4fc3f7' },
{ offset: 1, color: '#2196f3' }
]),
borderRadius: [4, 4, 0, 0]
},
animationDuration: 1500
}]
};
chart1.setOption(option1);
// 图表2: 折线图 - 交易金额趋势
const chart2 = echarts.init(document.getElementById('chart2'), 'dark');
const option2 = {
backgroundColor: 'transparent',
grid: { top: 30, right: 15, bottom: 25, left: 50 },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.5)' } },
axisLabel: { color: '#fff', fontSize: 10 }
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: 'rgba(83, 52, 131, 0.1)' } },
axisLabel: { color: '#fff', fontSize: 10, formatter: '¥{value}' }
},
series: [{
type: 'line',
data: [1.2, 1.5, 1.8, 2.1, 1.9, 2.5, 2.3],
smooth: true,
symbol: 'circle',
symbolSize: 6,
lineStyle: { color: '#e91e63', width: 3 },
itemStyle: { color: '#e91e63' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(233, 30, 99, 0.4)' },
{ offset: 1, color: 'rgba(233, 30, 99, 0.05)' }
])
},
animationDuration: 1500
}]
};
chart2.setOption(option2);
// 图表3: 饼图 - 系统负载分布
const chart3 = echarts.init(document.getElementById('chart3'), 'dark');
const option3 = {
backgroundColor: 'transparent',
series: [{
type: 'pie',
radius: ['35%', '65%'],
center: ['50%', '55%'],
data: [
{ value: 35, name: 'CPU', itemStyle: { color: '#4caf50' } },
{ value: 28, name: '内存', itemStyle: { color: '#2196f3' } },
{ value: 20, name: '磁盘', itemStyle: { color: '#ff9800' } },
{ value: 17, name: '网络', itemStyle: { color: '#9c27b0' } }
],
label: { color: '#fff', fontSize: 10 },
labelLine: { lineStyle: { color: 'rgba(255,255,255,0.5)' } },
animationDuration: 1500
}]
};
chart3.setOption(option3);
// 图表4: 仪表盘 - 响应时间
const chart4 = echarts.init(document.getElementById('chart4'), 'dark');
const option4 = {
backgroundColor: 'transparent',
series: [{
type: 'gauge',
radius: '75%',
center: ['50%', '55%'],
min: 0,
max: 100,
splitNumber: 10,
axisLine: {
lineStyle: {
width: 8,
color: [[0.3, '#4caf50'], [0.7, '#2196f3'], [1, '#f44336']]
}
},
pointer: { itemStyle: { color: '#4fc3f7' }, width: 4 },
axisTick: { distance: -8, length: 4, lineStyle: { color: '#fff' } },
splitLine: { distance: -8, length: 10, lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff', distance: -20, fontSize: 9 },
detail: {
valueAnimation: true,
formatter: '{value}ms',
color: '#4fc3f7',
fontSize: 16,
offsetCenter: [0, '65%']
},
data: [{ value: 23 }],
animationDuration: 2000
}]
};
chart4.setOption(option4);
// 响应式调整
const charts = [chart1, chart2, chart3, chart4];
window.addEventListener('resize', () => {
charts.forEach(chart => chart.resize());
});
// 模拟数据更新
setInterval(() => {
const newValue = Math.floor(Math.random() * 20) + 15;
chart4.setOption({ series: [{ data: [{ value: newValue }] }] });
}, 3000);
</script>
</body>
</html>
/* 使用 rem 单位编写样式 */
.header {
height: 1rem; /* 设计稿 100px */
font-size: 0.5rem; /* 设计稿 50px */
letter-spacing: 0.08rem;
}
.sidebar {
width: 4rem; /* 设计稿 400px */
padding: 0.2rem; /* 设计稿 20px */
}
.card-title {
font-size: 0.22rem; /* 设计稿 22px */
}
.card-value {
font-size: 0.56rem; /* 设计稿 56px */
}
完整 Demo 文件列表:
-
demo1- Scale 等比例缩放(上方已提供完整代码) -
demo2- VW/VH 视口单位方案 -
demo3- Rem 动态计算方案 -
demo4- 流式/弹性布局方案 -
demo5- 响应式断点方案 -
demo6- 混合方案(推荐)
以上所有demo均可在本地环境中直接运行,建议按顺序体验对比各方案的表现差异
核心代码示例
Scale 方案核心代码
<!DOCTYPE html>
<html>
<head>
<style>
.screen-container {
width: 1920px;
height: 1080px;
transform-origin: 0 0;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
}
</style>
</head>
<body>
<div class="screen-container" id="screen">
<!-- 大屏内容 -->
</div>
<script>
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;
function setScale() {
const scaleX = window.innerWidth / DESIGN_WIDTH;
const scaleY = window.innerHeight / DESIGN_HEIGHT;
const scale = Math.min(scaleX, scaleY);
const screen = document.getElementById('screen');
screen.style.transform = `scale(${scale})`;
// 居中显示
const left = (window.innerWidth - DESIGN_WIDTH * scale) / 2;
const top = (window.innerHeight - DESIGN_HEIGHT * scale) / 2;
screen.style.left = left + 'px';
screen.style.top = top + 'px';
}
setScale();
window.addEventListener('resize', setScale);
</script>
</body>
</html>
混合方案核心代码
// 混合方案:Scale + Rem
const DESIGN_WIDTH = 1920;
const DESIGN_HEIGHT = 1080;
const MIN_SCALE = 0.6; // 最小缩放限制,防止过小
function adapt() {
const winW = window.innerWidth;
const winH = window.innerHeight;
// Scale 计算
const scaleX = winW / DESIGN_WIDTH;
const scaleY = winH / DESIGN_HEIGHT;
const scale = Math.max(Math.min(scaleX, scaleY), MIN_SCALE);
// 应用 scale
const screen = document.getElementById('screen');
screen.style.transform = `scale(${scale})`;
// Rem 计算 - 根据缩放比例调整根字体
// 当 scale < 1 时,增加根字体补偿
const baseRem = 100;
const fontScale = Math.max(scale, MIN_SCALE);
const rem = baseRem * fontScale;
document.documentElement.style.fontSize = rem + 'px';
}
adapt();
window.addEventListener('resize', adapt);
总结
大屏适配没有银弹,每种方案都有其适用场景:
- 简单大屏项目:使用 Scale 方案,快速实现
- 内容管理系统:使用流式布局,灵活适配
- 移动端优先:使用 Rem 方案,成熟稳定
- 多端统一:使用混合方案,兼顾体验
选择方案时需要综合考虑:
- 设计稿还原要求
- 目标设备规格
- 开发维护成本
- 团队技术栈
希望本文能帮助你在大屏开发中游刃有余!
如果觉得有帮助,欢迎点赞收藏,有问题欢迎在评论区讨论!
手撕 Claude Code-4: TodoWrite 与任务系统
第 4 章:TodoWrite 与任务系统
源码位置:
src/tools/TodoWriteTool/、src/tasks/、src/utils/tasks.ts
4.1 两个容易混淆的概念
Claude Code 中有两个相关但不同的"任务"概念:
| 概念 | 说明 | 存储位置 |
|---|---|---|
| Todo(任务清单) | Claude 在当前会话中规划的工作步骤 | AppState.todos |
| Task(系统任务) | 运行时管理的实体(子代理、Shell 命令、后台会话等) | AppState.tasks |
本章先讲 TodoWrite(任务清单),再讲 Task System(系统任务)。
4.2 TodoWrite:Claude 的工作计划本
4.2.1 数据模型
// src/utils/todo/types.ts
type TodoItem = {
content: string // 任务描述
status: 'pending' | 'in_progress' | 'completed'
activeForm: string // 任务的主动形式(如 "Reading src/foo.ts")
}
type TodoList = TodoItem[]
4.2.2 工具实现
源码位置:src/tools/TodoWriteTool/TodoWriteTool.ts:65
async call({ todos }, context) {
const appState = context.getAppState()
// 每个代理有自己的 todo 列表(用 agentId 或 sessionId 区分)
const todoKey = context.agentId ?? getSessionId()
const oldTodos = appState.todos[todoKey] ?? []
// 关键逻辑:如果所有任务都已完成,AppState 中清空为 []
const allDone = todos.every(_ => _.status === 'completed')
const newTodos = allDone ? [] : todos
// 验证提醒:仅当 allDone && 3+ 项 && 无验证步骤时才触发
let verificationNudgeNeeded = false
if (
feature('VERIFICATION_AGENT') &&
getFeatureValue_CACHED_MAY_BE_STALE('tengu_hive_evidence', false) &&
!context.agentId && // 只在主线程触发,不在子代理
allDone && // 必须是关闭列表的那一刻
todos.length >= 3 &&
!todos.some(t => /verif/i.test(t.content))
) {
verificationNudgeNeeded = true
}
// 注意:API 是 setAppState(接收 prev → newState 函数),不是 updateAppState
context.setAppState(prev => ({
...prev,
todos: { ...prev.todos, [todoKey]: newTodos },
}))
// 返回值中 newTodos 是原始输入 todos(非清空后的 [])
return {
data: { oldTodos, newTodos: todos, verificationNudgeNeeded },
}
}
4.2.3 关键设计点
1. 所有完成即清空
当所有 todo 都标记为 completed,AppState 中的列表被清空为 [] 而不是保留所有已完成项。这避免了 token 浪费(每次 API 调用都要序列化已完成的任务)。注意:工具返回值中的 newTodos 字段仍为原始 todos 输入,清空仅影响 AppState 存储层。
2. agentId 隔离
每个子代理有独立的 todo 列表(通过 agentId 作为 key)。主线程用 sessionId。这样并行运行的子代理不会互相干扰。
3. shouldDefer: true
TodoWrite 被标记为延迟披露,不在每次 API 请求中直接包含其 Schema。Claude 通过 ToolSearch 找到它。
4. 与 TodoV2(Task API)互斥
源码位置:src/tools/TodoWriteTool/TodoWriteTool.ts:53 中:
isEnabled() {
return !isTodoV2Enabled()
}
源码位置:src/utils/tasks.ts:133
isTodoV2Enabled() 在以下情况返回 true(即 TodoWrite 被禁用):
- 环境变量
CLAUDE_CODE_ENABLE_TASKS=1 - 非交互式会话(SDK 模式)
这意味着 SDK 用户默认使用 Task API 而非 TodoWrite。
5. verificationNudgeNeeded
这是一个"行为引导"机制。触发条件(需同时满足):
- Feature flag
VERIFICATION_AGENT已开启(编译时 gate) - GrowthBook flag
tengu_hive_evidence为 true - 当前在主线程(
!context.agentId) - 当前调用正在关闭整个列表(
allDone === true) - 任务数 ≥ 3
- 没有任何任务内容匹配
/verif/i
满足时,工具结果会追加提示,要求 Claude 在写最终摘要前先 spawn 验证代理。
4.3 Task System:运行时实体管理
Task System 管理着 Claude Code 中所有的"运行中的实体"。
4.3.0 TaskStateBase:所有任务的公共基础
源码位置:src/Task.ts:45
type TaskStateBase = {
id: string // 任务 ID(带类型前缀,见下表)
type: TaskType // 'local_bash' | 'local_agent' | 'remote_agent' | 'in_process_teammate' | 'local_workflow' | 'monitor_mcp' | 'dream'
status: TaskStatus // 'pending' | 'running' | 'completed' | 'failed' | 'killed'
description: string
toolUseId?: string // 触发此任务的 tool_use block ID(用于通知回调)
startTime: number
endTime?: number
totalPausedMs?: number
outputFile: string // 磁盘输出文件路径(快照,/clear 后不变)
outputOffset: number // 已读取字节偏移量(用于增量 delta 读取)
notified: boolean // 是否已发送完成通知(防止重复通知)
}
Task ID 前缀表(src/Task.ts:79):
| 类型 | 前缀 | 示例 |
|---|---|---|
local_bash |
b |
b3f9a2c1 |
local_agent |
a |
a7d8e4f2 |
remote_agent |
r |
r2a1b3c4 |
in_process_teammate |
t |
t5e6f7a8 |
local_workflow |
w |
w9b0c1d2 |
monitor_mcp |
m |
m3e4f5a6 |
dream |
d |
d7b8c9d0 |
| 主会话(特殊) | s |
s1a2b3c4 |
local_agent和主会话后台化共用a前缀(LocalAgentTaskState),但主会话后台化通过LocalMainSessionTask.ts中独立的generateMainSessionTaskId()使用s前缀,与普通子代理区分。
4.3.1 TaskState 联合类型
源码位置:src/tasks/types.ts
// 注意:类型名是 TaskState,不是 Task
type TaskState =
| LocalShellTaskState // 长运行 Shell 命令
| LocalAgentTaskState // 本地子代理(含后台化主会话)
| RemoteAgentTaskState // 远程代理
| InProcessTeammateTaskState // in-process 队友(团队协作)
| LocalWorkflowTaskState // 工作流
| MonitorMcpTaskState // MCP 监控
| DreamTaskState // 记忆整合子代理(auto-dream)
注意:
LocalMainSessionTask不是独立的联合类型成员。它是LocalAgentTaskState的子类型:// src/tasks/LocalMainSessionTask.ts type LocalMainSessionTaskState = LocalAgentTaskState & { agentType: 'main-session' }这意味着后台化主会话与普通子代理共用同一个
type: 'local_agent'标识符,通过agentType字段区分。
4.3.2 主会话后台化(LocalMainSessionTask)
这是一个特殊功能:用户按 Ctrl+B 两次可以将当前对话"后台化",然后开始新的对话。后台化后,原查询继续在后台独立运行。
源码位置:src/tasks/LocalMainSessionTask.ts
// LocalMainSessionTaskState 不是独立类型,而是 LocalAgentTaskState 的子类型
type LocalMainSessionTaskState = LocalAgentTaskState & {
agentType: 'main-session' // 唯一区分标识
}
// type: 'local_agent'(继承)
// taskId: 's' 前缀(区分普通代理的 'a' 前缀)
// messages?: Message[](继承,存储后台查询的消息历史)
// isBackgrounded: boolean(继承,true = 后台,false = 前台展示中)
// 无独立 transcript 字段
关键函数:
// 注册后台会话任务,返回 { taskId, abortSignal }
registerMainSessionTask(description, setAppState, agentDefinition?, abortController?)
// 启动真正的后台查询(wrap runWithAgentContext + query())
startBackgroundSession({ messages, queryParams, description, setAppState })
// 将后台任务切回前台展示
foregroundMainSessionTask(taskId, setAppState): Message[]
为什么需要隔离的转录路径? 后台任务使用 getAgentTranscriptPath(agentId) 而不是主会话的路径。若用同一路径,/clear 会意外覆盖后台会话数据。后台任务通过 initTaskOutputAsSymlink() 创建软链接,/clear 重链接时不影响后台任务的历史记录。
4.3.3 本地代理任务(LocalAgentTask)
每个子代理对应一个 LocalAgentTaskState:
源码位置:src/tasks/LocalAgentTask/LocalAgentTask.tsx:116
type LocalAgentTaskState = TaskStateBase & {
type: 'local_agent'
agentId: string
prompt: string
selectedAgent?: AgentDefinition
agentType: string // 区分子类型,'main-session' = 后台化主会话
model?: string
abortController?: AbortController
error?: string
result?: AgentToolResult
progress?: AgentProgress // 进度信息(包含 toolUseCount、tokenCount)
retrieved: boolean // 结果是否已被取回
messages?: Message[] // 代理的消息历史(UI 展示用)
lastReportedToolCount: number
lastReportedTokenCount: number
isBackgrounded: boolean // false = 前台展示中,true = 后台运行
pendingMessages: string[] // SendMessage 排队的消息,在工具轮边界处理
retain: boolean // UI 持有此任务(阻止驱逐)
diskLoaded: boolean // 是否已从磁盘加载 sidechain JSONL
evictAfter?: number // 驱逐时间戳(任务完成后设置)
}
注意:文档中常见误写
toolUseCount为 LocalAgentTaskState 的直接字段,实际它在progress.toolUseCount中。status字段继承自TaskStateBase('running' | 'completed' | 'failed' | 'stopped')。
进度追踪通过专门的辅助函数:
// src/tasks/LocalAgentTask/LocalAgentTask.tsx
createProgressTracker() // 初始化 ProgressTracker(分别追踪 input/output tokens)
updateProgressFromMessage() // 从 assistant message 累积 token 和工具调用数
getProgressUpdate() // 生成 AgentProgress 快照(供 UI 消费)
createActivityDescriptionResolver() // 通过 tool.getActivityDescription() 生成人类可读描述
Token 追踪的精妙设计:ProgressTracker 分开存储 latestInputTokens(Claude API 累积值,取最新)和 cumulativeOutputTokens(逐轮累加),避免重复计数。
4.3.4 in-process 队友任务(InProcessTeammateTask)
这是 Agent Teams 的核心数据结构:
src/tasks/InProcessTeammateTask/types.ts
type TeammateIdentity = {
agentId: string // e.g., "researcher@my-team"
agentName: string // e.g., "researcher"
teamName: string
color?: string
planModeRequired: boolean
parentSessionId: string // Leader 的 sessionId
}
type InProcessTeammateTaskState = TaskStateBase & {
type: 'in_process_teammate'
identity: TeammateIdentity // 队友身份(存储在 AppState 中的 plain data)
prompt: string
model?: string
selectedAgent?: AgentDefinition
abortController?: AbortController // 终止整个队友
currentWorkAbortController?: AbortController // 终止当前轮次
awaitingPlanApproval: boolean // 是否等待 plan 审批
permissionMode: PermissionMode // 独立权限模式(Shift+Tab 切换)
error?: string
result?: AgentToolResult
progress?: AgentProgress
messages?: Message[] // UI 展示用(上限 50 条,TEAMMATE_MESSAGES_UI_CAP)
pendingUserMessages: string[] // 查看该队友时用户输入的队列消息
isIdle: boolean // 是否处于空闲(等待 leader 指令)
shutdownRequested: boolean // 是否已请求关闭
lastReportedToolCount: number
lastReportedTokenCount: number
}
常见误解:
mailbox字段不存在于InProcessTeammateTaskState。队友间的通信邮箱存储在运行时上下文teamContext.inProcessMailboxes(AsyncLocalStorage 中),不在 AppState 里。pendingUserMessages是用户从 UI 发给该队友的消息队列,与邮箱是两回事。
内存上限设计:messages 字段上限 50 条(TEAMMATE_MESSAGES_UI_CAP),超出后从头部截断。原因是生产环境出现过单个 whale session 启动 292 个 agent、内存达 36.8GB 的情况,根本原因正是此字段持有第二份完整消息副本。
4.3.5 记忆整合任务(DreamTask)
源码位置:src/tasks/DreamTask/DreamTask.ts
type DreamTaskState = TaskStateBase & {
type: 'dream'
phase: 'starting' | 'updating' // starting → updating(首个 Edit/Write 后翻转)
sessionsReviewing: number // 正在整理的会话数量
filesTouched: string[] // 被 Edit/Write 触碰的文件(不完整,仅 pattern-match 到的)
turns: DreamTurn[] // assistant 轮次(工具调用折叠为计数)
abortController?: AbortController
priorMtime: number // 用于 kill 时回滚 consolidationLock 时间戳
}
DreamTask 是"auto-dream"记忆整合的 UI 表面层。它不改变子代理运行逻辑,只是让原本不可见的 fork agent 在 footer pill 和 Shift+Down 对话框中可见。子代理按 4 阶段 prompt 运行(orient → gather → consolidate → prune),但 DreamTask 不解析阶段,只通过工具调用类型推断 phase。
4.4 任务注册与生命周期框架
源码位置:src/utils/task/framework.ts
4.4.1 registerTask:注册与恢复
registerTask(task: TaskState, setAppState): void
注册一个新任务时,有两条路径:
新建(existing === undefined):
- 将 task 写入
AppState.tasks[task.id] - 向 SDK 事件队列发出
task_started事件
恢复/替换(existing !== undefined,如 resumeAgentBackground):
- 合并保留以下 UI 状态(避免用户正在查看的面板闪烁):
-
retain:UI 持有标记 -
startTime:面板排序稳定性 -
messages:用户刚发送的消息还未落盘 -
diskLoaded:避免重复加载 sidechain JSONL -
pendingMessages:待处理消息队列
-
-
不发出
task_started(防止 SDK 重复计数)
4.4.2 任务完成通知(XML 格式)
子代理/后台任务完成时,通过 enqueuePendingNotification 将 XML 推入消息队列:
<task_notification>
<task_id>a7d8e4f2</task_id>
<tool_use_id>toolu_01xxx</tool_use_id> <!-- 可选 -->
<output_file>/tmp/.../tasks/a7d8e4f2.output</output_file>
<status>completed</status>
<summary>Task "修复登录 bug" completed successfully</summary>
</task_notification>
这段 XML 在下一轮 API 调用前作为 user 消息被注入 messages,使 LLM 感知到后台任务完成。
4.4.3 evictTerminalTask:两级驱逐
任务完成后并不立即从 AppState.tasks 中删除,而是两级驱逐:
任务完成 → status='completed' + notified=true
│
├─ 如果 retain=true 或 evictAfter > Date.now()
│ → 保留(UI 正在展示,等待 30s grace period 后驱逐)
│
└─ 否则 → 立即从 AppState.tasks 中删除(eagerly evict)
作为保底,generateTaskAttachments() 也会在下次 poll 时驱逐
PANEL_GRACE_MS = 30_000(30秒)是 coordinator panel 中 agent 任务的展示宽限期,确保用户能看到结果后再消失。
4.5 后台 API 任务工具
用户(通过 Claude)可以创建和管理后台任务:
// TaskCreateTool / TaskUpdateTool / TaskStopTool / TaskGetTool / TaskListTool
这些工具允许 Claude 自己创建和监控后台任务,实现真正的异步多任务处理。注意:这套 Task API 工具仅在 TodoV2 模式下启用(即 isTodoV2Enabled() === true),与 TodoWrite 互斥。
4.6 任务输出的磁盘管理
源码位置:src/utils/task/diskOutput.ts
4.6.1 输出文件路径
// 注意:路径不是 .claude/tasks/,而是项目临时目录下的会话子目录
getTaskOutputPath(taskId) → `{projectTempDir}/{sessionId}/tasks/{taskId}.output`
为什么包含 sessionId? 防止同一项目的并发 Claude Code 会话互相踩踏输出文件。路径在首次调用时被 memoize(let _taskOutputDir),/clear 触发 regenerateSessionId() 时不会重新计算,确保跨 /clear 存活的后台任务仍能找到自己的文件。
4.6.2 DiskTaskOutput 写队列
任务输出通过 DiskTaskOutput 类异步写入磁盘:
class DiskTaskOutput {
append(content: string): void // 入队,自动触发 drain
flush(): Promise<void> // 等待队列清空
cancel(): void // 丢弃队列(任务被 kill 时)
}
核心设计要点:
-
写队列:
#queue: string[]平铺数组,单个 drain 循环消费,chunk 写入后立即可被 GC,避免.then()链持有引用导致内存膨胀 -
5GB 上限:超限后追加截断标记并停止写入:
[output truncated: exceeded 5GB disk cap] -
O_NOFOLLOW 安全:Unix 上用
O_NOFOLLOWflag 打开文件,防止沙箱中的攻击者通过创建软链接将 Claude Code 写入任意宿主文件 -
事务追踪:所有 fire-and-forget 异步操作(
initTaskOutput、evictTaskOutput等)注册到_pendingOps: Set<Promise>,测试可通过allSettled等待全部完成,防止跨测试的 ENOENT 竞争
4.6.3 增量输出读取(OutputOffset)
TaskStateBase.outputOffset 记录已消费的字节偏移,实现增量读取:
// 仅读取 fromOffset 之后的新内容(最多 8MB)
getTaskOutputDelta(taskId, fromOffset): Promise<{ content: string; newOffset: number }>
framework.ts 中的 generateTaskAttachments() 在每次 poll 时调用 getTaskOutputDelta,将新增内容附加到 task_status attachment 中推送给 LLM,避免重复加载完整输出文件。
4.6.4 关键函数对比
| 函数 | 是否删磁盘文件 | 是否清内存 | 适用场景 |
|---|---|---|---|
evictTaskOutput(taskId) |
否 | 是(flush 后清 Map) | 任务完成,结果已消费 |
cleanupTaskOutput(taskId) |
是 | 是 | 彻底清理(测试、取消) |
flushTaskOutput(taskId) |
否 | 否 | 读取前确保写入完成 |
4.7 Cron 定时任务
通过 Cron 工具,可以创建定期自动运行的任务:
// CronCreate / CronDelete / CronList 工具
// 底层通过 src/utils/cron.ts 管理
// 使用示例(Claude 会这样调用):
// CronCreate({ schedule: '0 9 * * 1', command: '/review-pr' })
// → 每周一早上 9 点自动运行 /review-pr
4.8 流程图:任务的完整生命周期
用户输入复杂任务
│
▼
Claude 调用 TodoWrite ← 规划工作步骤
todos: [
{ content: '读取代码', status: 'pending' },
{ content: '修改功能', status: 'pending' },
{ content: '运行测试', status: 'pending' },
]
│
▼
Claude 开始执行第一步
TodoWrite: { status: 'in_progress' } ← 标记进行中
│
├─ 如果需要并行工作:
│ Agent({ subagent_type: 'general-purpose', ... })
│ │
│ ▼
│ 创建 LocalAgentTaskState(id: 'a-xxxxxxxx',agentId 同值)
│ 子代理在独立上下文中运行
│ │
│ ▼
│ 子代理有自己的 Todo 列表(隔离)
│
▼
每步完成后:
TodoWrite: { status: 'completed' } ← 标记完成
│
▼
所有步骤完成:
TodoWrite: todos.every(done) → 清空列表 []
│
▼
Agent Loop 检测到无工具调用 → 停止
小结
| 组件 | 职责 | 源码位置 |
|---|---|---|
TodoWriteTool |
会话内工作计划追踪(交互模式) | src/tools/TodoWriteTool/TodoWriteTool.ts |
| Task API 工具 | 后台任务创建与管理(SDK/非交互模式) |
TaskCreateTool / TaskStopTool 等 |
TaskStateBase |
所有任务的公共字段(含 id、status、outputOffset) | src/Task.ts |
LocalMainSessionTask |
主会话后台化(LocalAgentTaskState 子类型) |
src/tasks/LocalMainSessionTask.ts |
LocalAgentTaskState |
子代理生命周期管理 | src/tasks/LocalAgentTask/LocalAgentTask.tsx |
InProcessTeammateTaskState |
团队队友状态(含内存上限 50 条) | src/tasks/InProcessTeammateTask/types.ts |
DreamTaskState |
记忆整合子代理的 UI 表面层 | src/tasks/DreamTask/DreamTask.ts |
| 任务框架 | registerTask / evictTerminalTask / 通知 XML | src/utils/task/framework.ts |
| 磁盘输出管理 | DiskTaskOutput 写队列 / 增量读取 / 5GB 上限 | src/utils/task/diskOutput.ts |
| Cron 定时任务 | 自动化周期任务 |
CronCreate/Delete/List 工具 |
关键设计约定总结:
| 约定 | 说明 |
|---|---|
LocalMainSessionTask 不是独立类型 |
它是 LocalAgentTaskState & { agentType: 'main-session' }
|
| TaskState(不是 Task) | 联合类型的正确名称 |
setAppState(不是 updateAppState) |
AppState 更新的实际 API |
toolUseCount 在 progress 内 |
不是 LocalAgentTaskState 的直接字段 |
| TodoWrite 与 Task API 互斥 | 通过 isTodoV2Enabled() 在 isEnabled() 中切换 |
【节点】[DDY节点]原理解析与实际应用
DDY 节点是 Unity URP Shader Graph 中一个重要的高级功能节点,它提供了在像素着色器阶段计算屏幕空间 Y 方向偏导数的能力。这个节点基于 GPU 的导数计算硬件,能够高效地获取相邻像素间的数值变化率,在计算机图形学中有着广泛的应用场景。
偏导数的概念源自微积分,在图形学上下文中,它表示某个值在屏幕空间相邻像素间的变化率。DDY 节点专门计算 Y 方向(垂直方向)的变化率,而与之对应的 DDX 节点则计算 X 方向(水平方向)的变化率。这两个节点共同构成了现代 GPU 并行架构中导数计算的核心功能。
在 Shader Graph 中使用 DDY 节点时,理解其工作原理和限制条件至关重要。由于该节点依赖于像素着色器中的片段并行处理特性,它只能在特定的渲染阶段使用,并且对硬件有一定的要求。掌握 DDY 节点的正确使用方法,能够为着色器开发带来更多可能性,实现各种高级视觉效果。
描述
DDY 节点的核心功能是计算输入值在屏幕空间 Y 坐标方向上的偏导数。从数学角度理解,偏导数描述了多变量函数沿某一坐标轴方向的变化率。在着色器编程的语境中,这意味着 DDY 节点能够测量某个着色器属性或计算值在垂直相邻像素之间的差异。
屏幕空间偏导数的计算基于 GPU 的硬件特性。现代 GPU 通常以 2x2 像素块为单位并行执行像素着色器,这种架构被称为"像素四边形"(Pixel Quad)。在这种结构中,DDY 节点通过比较当前像素与同一像素四边形中下方像素的数值差异来计算偏导数。这种硬件级的并行计算使得导数计算非常高效,不需要额外的复杂数学运算。
DDY 节点的一个重要限制是它只能在像素着色器阶段使用。这是因为导数计算依赖于片段着色器中的像素级并行处理。如果尝试在顶点着色器或其他渲染阶段使用 DDY 节点,将会导致编译错误或未定义的行为。在 Shader Graph 中,当将 DDY 节点连接到非像素着色器阶段的节点时,系统通常会发出警告或错误提示。
在实际应用中,DDY 节点最常见的用途包括:
- 计算法线贴图的表面法线
- 实现基于导数的边缘检测
- 创建各向异性高光效果
- 优化纹理采样和 mipmap 级别选择
- 实现屏幕空间的环境光遮蔽
理解 DDY 节点的数学原理对于正确使用它至关重要。偏导数的计算可以近似表示为:ddy(p) ≈ p(x, y+1) - p(x, y),其中 p 是输入值,(x, y) 是当前像素的屏幕坐标。这个近似计算由 GPU 硬件在像素四边形级别自动完成,为着色器程序员提供了高效的导数访问方式。
端口
![]()
DDY 节点的端口设计遵循 Shader Graph 的标准约定,提供了清晰的输入输出接口,使得节点能够灵活地集成到各种着色器网络中。
输入端口
输入端口标记为 "In",是节点的唯一输入通道,接受动态矢量类型的数据。动态矢量意味着该端口可以接受各种维度的向量输入,包括:
- float(标量值)
- float2(二维向量)
- float3(三维向量)
- float4(四维向量)
这种灵活性使得 DDY 节点能够处理各种类型的数据,从简单的灰度值到完整的颜色信息。当输入多维向量时,DDY 节点会独立计算每个分量的偏导数,返回一个与输入维度相同的输出向量。
输入值的内容可以是任何在像素着色器中有效的表达式或节点输出,包括:
- 纹理采样结果
- 数学运算输出
- 时间变量
- 顶点数据插值
- 其他自定义计算的结果
输出端口
输出端口标记为 "Out",提供计算得到的偏导数结果。与输入端口类似,输出也是动态矢量类型,其维度与输入保持一致。输出值的每个分量对应于输入向量相应分量的偏导数。
输出值的范围和特性取决于输入内容:
- 当输入是连续平滑变化的值时,输出通常较小且变化平缓
- 当输入在相邻像素间有剧烈变化时,输出值会相应增大
- 在边缘或高对比度区域,输出值可能显著增加
- 在平坦或均匀区域,输出值接近零
理解输出值的这些特性对于正确解释和使用 DDY 节点的结果至关重要。在实际应用中,通常需要对输出值进行适当的缩放、钳制或后续处理,以适应特定的视觉效果需求。
端口连接实践
在 Shader Graph 中连接 DDY 节点时,需要考虑数据类型和精度的匹配。虽然动态矢量端口提供了很大的灵活性,但最佳实践包括:
- 确保输入数据的范围合理,避免极端值导致导数计算不稳定
- 注意数据精度,在移动平台或性能受限环境下考虑使用半精度浮点数
- 合理组织节点网络,避免不必要的复杂连接影响可读性
- 使用适当的注释和分组,使包含 DDY 节点的复杂网络更易于理解和维护
生成的代码示例
DDY 节点在背后生成的代码揭示了其在底层着色器语言中的实现方式。理解这些生成的代码有助于深入掌握节点的行为特性,并在需要时进行自定义扩展或优化。
HLSL 代码实现
在大多数情况下,DDY 节点会生成类似于以下示例的 HLSL 代码:
void Unity_DDY_float4(float4 In, out float4 Out)
{
Out = ddy(In);
}
这个简单的函数封装了 HLSL 内置的 ddy() 函数,该函数是 DirectX 着色器语言中用于计算屏幕空间 Y 方向偏导数的原生指令。函数接受一个 float4 类型的输入参数,并输出相应的偏导数结果。
对于不同维度的输入,生成的函数签名会相应调整:
- 对于 float 输入:
Unity_DDY_float(float In, out float Out) - 对于 float2 输入:
Unity_DDY_float2(float2 In, out float2 Out) - 对于 float3 输入:
Unity_DDY_float3(float3 In, out float3 Out)
底层硬件实现
虽然从代码层面看,DDY 节点的实现很简单,但它在硬件层面的执行却涉及 GPU 的并行架构特性。当 GPU 执行包含 ddy() 调用的像素着色器时:
- 着色器单元以 2x2 像素块(像素四边形)为单位调度执行
- 在每个像素四边形中,四个片段并行处理
- 硬件自动比较同一四边形中垂直相邻像素的寄存器值
- 计算得到的导数值用于所有四个像素的着色计算
这种实现方式意味着导数计算基本上没有额外的性能开销,因为 GPU 本来就需要并行处理像素四边形中的多个片段。这也是为什么导数计算只能在像素着色器中工作的原因——其他着色器阶段没有这种并行处理架构。
精度和性能考虑
在使用 DDY 节点时,了解其精度特性和性能影响很重要:
- 导数计算基于实际执行的像素值,因此结果完全准确
- 在几何边缘或遮挡边界处,导数可能不太可靠,因为相邻像素可能属于不同物体
- 性能开销通常很小,但在低端移动设备上,复杂的导数计算网络仍可能影响性能
- 在某些情况下,使用近似计算方法可能比直接使用 DDY 节点更高效
自定义扩展和应用
通过理解生成的代码模式,开发者可以创建自定义的导数计算函数,扩展 DDY 节点的功能:
// 自定义带缩放的导数计算
void Custom_DDY_Scaled(float4 In, float Scale, out float4 Out)
{
Out = ddy(In) * Scale;
}
// 带钳制的导数计算,避免过大的导数值
void Custom_DDY_Clamped(float4 In, float MaxDerivative, out float4 Out)
{
Out = clamp(ddy(In), -MaxDerivative, MaxDerivative);
}
// 计算导数的大小,用于边缘检测等应用
void Custom_DDY_Length(float4 In, out float Out)
{
Out = length(ddy(In));
}
这些自定义函数可以在 Shader Graph 中通过 Custom Function 节点实现,为特定的应用场景提供更专门的导数计算功能。
实际应用案例
DDY 节点在着色器开发中有着广泛的应用,以下是一些典型的实际应用案例,展示了如何充分利用这个节点的特性。
法线贴图处理
在基于物理的渲染中,法线贴图是增强表面细节的关键技术。DDY 节点可以用于计算法线贴图的正确 mipmap 级别,或者在需要时重建世界空间法线:
// 使用 DDY 计算法线贴图的适当 LOD 级别
float CalculateNormalMapLOD(float2 uv)
{
float2 deriv = float2(ddx(uv.x), ddy(uv.y));
float lod = 0.5 * log2(max(dot(deriv, deriv), 1.0));
return lod;
}
// 结合 DDX 和 DDY 重建世界空间法线
float3 ReconstructWorldNormal(float2 uv, float3 normalTS, float3x3 TBN)
{
float3 ddx_normal = ddx(normalTS);
float3 ddy_normal = ddy(normalTS);
// 应用复杂的法线重建算法
// ...
}
边缘检测效果
DDY 节点在屏幕后处理中常用于边缘检测,通过分析颜色或深度的变化来识别图像中的边缘:
// 基于颜色导数的简单边缘检测
float EdgeDetectionColor(float2 uv, sampler2D colorTexture)
{
float3 color = tex2D(colorTexture, uv).rgb;
float3 deriv_x = ddx(color);
float3 deriv_y = ddy(color);
float edge = length(deriv_x) + length(deriv_y);
return saturate(edge * 10.0); // 调整灵敏度
}
// 结合深度和颜色的高级边缘检测
float AdvancedEdgeDetection(float2 uv, sampler2D colorTexture, sampler2D depthTexture)
{
float depth = tex2D(depthTexture, uv).r;
float3 color = tex2D(colorTexture, uv).rgb;
float depth_edge = abs(ddy(depth)) * 100.0; // 深度边缘
float color_edge = length(ddy(color)) * 10.0; // 颜色边缘
return saturate(max(depth_edge, color_edge));
}
各向异性高光
各向异性高光效果模拟表面在特定方向反射光线的特性,如拉丝金属或头发材质。DDY 节点可以帮助确定高光的方向和强度:
// 简单的各向异性高光计算
float AnisotropicSpecular(float3 worldNormal, float3 viewDir, float2 uv)
{
// 使用 UV 导数确定各向异性方向
float2 deriv = float2(ddx(uv.x), ddy(uv.y));
float anisotropy = length(deriv);
// 基于导数方向调整高光
float3 anisotropicDir = normalize(float3(deriv.x, deriv.y, 0));
// 进一步的高光计算...
return specular;
}
纹理采样优化
通过分析纹理坐标的导数,可以优化纹理采样,选择适当的 mipmap 级别,平衡质量和性能:
// 基于导数的自适应纹理采样
float4 AdaptiveTextureSample(sampler2D tex, float2 uv)
{
// 计算纹理坐标的导数
float2 duv_dx = ddx(uv);
float2 duv_dy = ddy(uv);
// 计算适当的 LOD 级别
float lod = 0.5 * log2(max(dot(duv_dx, duv_dx), dot(duv_dy, duv_dy)));
// 使用计算出的 LOD 进行采样
return tex2Dlod(tex, float4(uv, 0, lod));
}
最佳实践和注意事项
为了确保 DDY 节点的正确使用和最佳性能,遵循一些最佳实践和注意事项非常重要。
平台兼容性
DDY 节点在不同平台和图形 API 上的支持程度可能有所差异:
- 在所有现代桌面 GPU(DirectX 11+、Vulkan、Metal)上完全支持
- 在移动平台上,需要 OpenGL ES 3.0+ 或 Vulkan 支持
- 在较旧的硬件或图形 API 上可能有限制或性能问题
- 在 WebGL 中,支持程度取决于浏览器和硬件能力
为了确保跨平台兼容性,建议:
- 在图形设置中配置适当的回退方案
- 使用 Shader Graph 的条件编译功能处理平台差异
- 在移动平台上测试导数计算的性能影响
性能优化
虽然 DDY 节点本身很高效,但在复杂着色器中仍需注意性能:
- 避免在循环或复杂控制流中过度使用 DDY 节点
- 考虑复用导数计算结果,而不是重复计算
- 对于简单的应用,考虑使用近似的分析方法代替精确的导数计算
- 在性能敏感的平台,评估使用 DDY 节点的实际性能影响
数学精度考虑
导数计算对数值精度很敏感,特别是在 HDR 或高动态范围场景中:
- 注意输入值的范围,过大的值可能导致导数计算不稳定
- 在需要高精度的应用中,考虑使用更高精度的浮点数格式
- 注意导数计算在 discontinuities(不连续点)处的行为可能不符合预期
调试和可视化
调试包含 DDY 节点的着色器可能具有挑战性,以下技巧可以帮助:
- 使用 Color 节点将导数值可视化,检查其范围和分布
- 创建调试视图,单独显示导数计算的结果
- 使用适当的缩放和偏移,使导数值在可视范围内
- 在简单测试案例中验证导数计算的行为
与其他节点的结合
DDY 节点通常与其他数学和工具节点结合使用,创建复杂的视觉效果:
- 结合 DDX 节点获取完整的梯度信息
- 使用数学节点对导数结果进行后处理
- 与条件节点结合,创建基于导数阈值的效果
- 在子图中封装复杂的导数计算逻辑,提高可重用性
【Unity Shader Graph 使用与特效实现】专栏-直达 (欢迎点赞留言探讨,更多人加入进来能更加完善这个探索的过程,🙏)
深度起底 Vite:从打包流程到插件钩子执行时序的全链路解析
前言
Vite 之所以能颠覆 Webpack 的统治地位,不仅是因为它在开发阶段的“快”,更在于它巧妙地结合了 原生 ESM 与 Rollup 的生产构建能力。本文将带你拆解 Vite 打包的每一个步骤,并揭秘其插件系统的核心钩子。
一、 Vite 生产打包流水线
Vite 的生产构建完全基于 Rollup 实现,但在 Rollup 打包前后增加了 Vite 特有的预处理和后优化步骤,整个流程可以分为以下 6 个核心阶段:
步骤 1:加载并解析配置
Vite 会优先读取项目根目录的vite.config.js/ts(或vite.config.mjs)配置文件,同时合并命令行参数和默认配置,形成最终的运行配置。
- 解析核心配置项:
root(项目根目录)、base(公共基础路径)、build(打包配置,如输出目录、目标环境、代码分割等)、plugins(插件)、resolve(路径解析)等 - 同时会读取
package.json中的type: module等配置,确定项目的模块规范
配置合并优先级为:命令行参数 > 配置文件导出的配置 > Vite 内置默认配置
步骤 2:预构建与依赖分析
这是 Vite 区别于传统打包工具的关键步骤,主要为了解决第三方依赖的兼容性和打包性能问题。
- Vite 会扫描项目中的所有依赖(主要是
node_modules中的第三方包),对非 ES 模块的依赖(如 CommonJS、UMD 格式)进行预构建,统一转换为标准 ES 模块 - 分析项目入口文件(默认是根目录的
index.html),递归解析所有文件的依赖关系(包括.vue/.js/.ts/.css/.scss等各种类型的文件),构建完整的模块依赖图
补充:预构建的结果会被缓存到
node_modules/.vite目录,只有当依赖发生变化时才会重新预构建,极大提升了后续打包速度
步骤 3:插件执行
Vite 会按照配置的顺序依次执行所有插件,并调用相应的插件生命周期钩子,在这个阶段完成各种文件转换、代码预处理和资源处理操作。
-
插件会在不同的生命周期钩子中执行对应的逻辑,例如:
- 对
.vue/.jsx/.tsx等非原生 JS 文件进行编译转换 - 小图片 / 字体等静态资源的 base64 转换(由 Vite 内置的 assets 插件处理)
- CSS 预处理器编译、PostCSS 处理、CSS Modules 转换等
- 对
步骤 4:使用 Rollup 进行核心打包
这是生产构建的核心阶段,Vite 将完全委托给 Rollup 进行代码打包和优化。
- 按入口文件拆分代码块(chunk),同时支持根据动态导入
import()自动拆分代码块,还可以通过配置将第三方依赖单独拆分为 vendor chunk - 生成兼容目标环境的代码:默认打包为现代浏览器支持的 ES 模块格式,也可通过
build.target配置兼容 ES5 及更低版本 - 处理模块间的依赖引用:将代码中的相对路径替换为配置的
base路径,确保生产环境下所有资源都能正确加载 - 执行 Rollup 特有的优化:包括 Tree Shaking 移除无用代码、作用域提升(Scope Hoisting)减少代码体积等
步骤 5:Rollup 产物最终优化
在 Rollup 完成基础打包后,Vite 会对输出的产物进行最后一轮的生产环境优化。
- 对 JavaScript 和 CSS 代码进行压缩混淆(默认使用 Terser 压缩 JS,esbuild 压缩 CSS)
- 生成资源哈希文件名,实现静态资源的长效缓存
- 可选生成 sourcemap 文件,方便生产环境调试
- 可选生成
manifest.json文件,记录资源文件名与哈希后的文件名的映射关系,用于后端集成
步骤 6:输出最终产物
将所有打包和优化后的产物输出到指定的目录(默认是dist目录)。
- 静态资源(JS、CSS、图片、字体等)会输出到
dist/assets目录 - 入口 HTML 文件会输出到
dist根目录 - 其他配置的静态资源会按照原目录结构输出到
dist目录
二、 揭秘 Vite 插件钩子 (Hooks)
Vite 的插件系统扩展自 Rollup 的插件系统,同时增加了一些 Vite 特有的钩子函数,以支持开发服务器和热更新等 Vite 独有的功能。
2.1 通用 Rollup 兼容钩子
Vite 在开发阶段会模拟 Rollup 的行为,调用一系列与 Rollup 兼容的钩子;而在生产环境下,由于 Vite 直接使用 Rollup 进行打包,所有 Rollup 插件钩子都会生效。
这些通用钩子主要分为三个阶段:
-
服务器启动阶段:
options和buildStart钩子会在开发服务启动时被调用 -
请求响应阶段:当浏览器发起请求时,Vite 内部依次调用
resolveId、load和transform钩子 -
服务器关闭阶段:Vite 会依次执行
buildEnd和closeBundle钩子
重要说明:除了以上钩子,其他 Rollup 插件钩子(如moduleParsed、renderChunk等)均不会在 Vite 开发阶段调用。这是因为开发阶段 Vite 采用按需编译的模式,不需要对整个项目进行完整打包。
2.2 Vite 独有钩子
Vite 提供了一些独有的钩子函数,这些钩子只会在 Vite 内部调用,放到纯 Rollup 环境中会被直接忽略。
| 钩子名称 | 调用时机 | 主要用途 |
|---|---|---|
config |
Vite 读取完配置文件之后,最终配置合并之前 | 对用户导出的配置对象进行自定义修改,例如注入默认值、根据环境动态调整配置、合并插件配置等 |
configResolved |
Vite 完成最终配置解析之后 | 此时配置已完全合并且不可再修改,常用于获取最终配置进行调试,或根据最终配置初始化插件内部状态 |
configureServer |
仅在开发服务器启动时调用 | 扩展或拦截开发服务器行为,例如添加自定义中间件、模拟 API 接口、修改服务器配置、实现请求代理等 |
transformIndexHtml |
转换原始 HTML 文件内容时调用 | 动态修改 index.html 内容,例如注入脚本标签、修改 meta 标签、添加全局变量、SSR 内容注入等 |
handleHotUpdate |
Vite 服务端处理热更新时调用 | 自定义热更新逻辑,例如过滤不需要热更新的模块、触发自定义的热更新行为、向客户端发送自定义消息等 |
三、 核心:钩子函数的执行顺序
理解执行顺序是编写高质量插件的前提。
1. 服务启动阶段
config → configResolved → options → configureServer → buildStart
2. 请求响应阶段
-
HTML 请求:仅执行
transformIndexHtml。 -
非 HTML 请求 (JS/CSS等):
resolveId→load→transform。
3. 热更新与关闭阶段
-
HMR 触发:
handleHotUpdate。 -
服务关闭:
buildEnd→closeBundle。
四、 知识扩展:开发与生产的差异
-
开发阶段:Vite 利用浏览器原生 ESM,只有在文件被请求时才触发
transform钩子,这是其“快”的底层逻辑。 - 生产阶段:Vite 完完全全变成了一个“Rollup 配置封装器”,所有插件钩子都会遵循 Rollup 的打包逻辑执行。
亚洲开发银行行长:货币和财政纪律是抵御重大外部冲击的最佳缓冲
Superpowers 从“调教提示词”转向“构建工程规范”
前言
最近留意到github上有个编程skills比较火爆superpowers , 很多人第一眼会觉得 superpowers 是一个“AI 编程插件”, 但我更倾向把它理解为一套约束 AI 行为的执行协议(Execution Protocol), 什么意思?在 Cursor 或 Codex 里:你输入 prompt, AI 自由发挥,本质是:无约束生成。而 superpowers 做的事情是:
- 把整个过程拆成多个阶段
- 每个阶段有明确输入 / 输出
- 严格限制 AI 当前“能做什么”
一、 我们正在面临的“AI 协作困境”
在superpowers实现前,先聊聊目前 AI 编程里最扎心的三个痛点:
-
认知边界的迷失 (Context Drift): AI 是个典型的“局部主义者”。在几万行的代码库里,它往往只盯着你喂给它的那几个文件。它不知道你项目里已经封装好了
axios,于是自作聪明地又写了一个。结果就是:项目跑通了,但代码复用度降低了。 - 调试的“黑盒”陷阱: 当代码报错时,AI 最常见的反应是“复读机式修复”。它会说“抱歉,我漏了一个判空”,改完报错;再说“抱歉,可能是异步问题”,再改。这种 Trial-and-Error(盲碰)的模式,不仅浪费 Token,更是在消磨开发者的耐心。
- 审查负担 (Review Fatigue): 现在最累的不是写代码,是 Review。AI 甩给你 500 行改动,你敢合吗?因为缺乏可信的验证路径,你甚至觉得 Review 它的代码比自己重写一遍还累。
二、 核心哲学:工程纪律大于模型能力
superpowers 的核心逻辑是:与其期待模型更聪明,不如让它的行为更规范。
在没有 superpowers 之前,AI 编程助手(如 Cursor、Claude)更像是一个极速打字员,而有了它之后,AI 变成了一个资深工程师。
2.1 强制性的“先思后行”(The Thinking Protocol)
- 普通 AI: 看到需求直接开改,改完发现引出 3 个新 Bug。
-
Superpowers AI: 被禁止直接动代码。它必须先调用
research技能查阅现有逻辑,再调用plan技能产出方案,最后才动手。这种认知顺序的强制化,极大地减少了“重构灾难”。
2.2 系统化调试(Systematic Debugging)
这是该项目最硬核的优势。它将调试从“碰运气”升级为“科学实验”:
- 它要求 AI 必须通过 Observation(观察) -> Hypothesis(假设) -> Verification(验证) 的闭环。
- AI 不能只说“修好了”,必须提供测试通过的证据。
2.3 环境隔离与安全(Isolation)
利用 git-worktree 技能,AI 的所有实验性修改都在平行空间进行。这让开发者敢于让 AI 进行大规模重构,因为一键即可回滚,主开发分支永远处于受保护状态。
三、 技术底层:它是如何“驯服”AI 的?
superpowers 的底层逻辑并非改变了 LLM(大模型)本身,而是通过工程抽象重新定义了人机交互的边界。
3.1 状态机模型(State Machine)
superpowers 将软件开发抽象成了一个有状态的流程。它定义了不同的“运行等级”:
-
Level 0: Context Gathering(只允许搜索和读取)
-
Level 1: Planning(产出文档,禁止改码)
-
Level 2: Execution(激活文件写入,配合 TDD)
这种物理层面的权限截断,确保了 AI 不会在还没搞懂逻辑时就开始乱写。
3.2 Skill 作为“原子化执行协议”
在源码中,每一个 .md 文件(如 systematic-debugging.md)都是一个 Skill 定义。它的原理包括:
- JSON Schema 绑定: 每个技能对应一组工具调用指令。当 AI 调用技能时,它必须填入符合规范的参数。
- 反馈闭环: 技能执行后,结果会以标准格式返回给 AI。如果 AI 没有按照协议(协议要求先写测试),系统会拒绝执行后续动作。
3.3 基于“上下文修剪”的精准控制
加载全量技能会造成 Token 溢出且让 AI 产生干扰。superpowers 的实现逻辑是:
-
动态注入: 根据当前任务阶段,动态地将相关的
SKILLS.md内容注入到 System Message 中。 - 少即是多: 限制 AI 在特定时刻能看到的“超能力”,反而提高了它的执行精度。
2.4 为什么它更稳定?
我们可以用一个公式来总结它的原理:
- 模型(LLM): 提供推理基础。
-
约束(Constraints): 由
superpowers提供。
它通过把软件工程的最佳实践(Best Practices)转化为模型必须遵守的原子化指令(Atomic Skills) ,实现了从“概率性代码生成”向“确定性工程闭环”的跨越。
一句话总结: superpowers 的核心不是给 AI 自由,而是给 AI 划定了一条“通往成功的狭窄路径”。
四、 实战:AI 视角下的“重构三部曲”
假设我们要重构一个逻辑混乱的老旧模块,在 superpowers 的加持下,AI 的执行路径是这样的:
4.1:Brainstorming(拒绝直接上手)
AI 接收任务后,第一步是调用 search 和 list_files 摸清家底。它会先输出一个“重构提案”,问你: “我发现这里有三个依赖项,我打算先解耦 A 再改动 B,你觉得呢?” 这种先提问、出方案的习惯,像极了靠谱的架构师。
4.2 环境隔离 (Git Worktrees)
为了保证安全,它会自动创建一个 Git Worktree。这意味着 AI 的所有折腾都在一个隔离的平行空间进行。即便它把代码改得一塌糊涂,也不会影响你当前的工作区。这种自动化运维的能力,让 AI 真正具备了“独立作业”的条件。
4.3 根因追踪 (Systematic Debugging)
遇到一个深层 Bug 时,AI 不再盲目改代码,而是开始执行“系统化观测”。它会先插入 Trace 日志,观察数据流,确认假设后才落笔。这种逻辑闭环,让它的修复成功率呈指数级提升。
五、 总结:AI 时代,我们该学什么?
随着 superpowers 这类工具的成熟,开发者的角色正在发生深刻转变:
我们不再是写代码的人,而是定义“产品”和检查“实现”的人。
与其在提示词里求 AI “请写得好一点”,不如像 superpowers 这样,给它一套标准化的技能说明书。如果你所在的团队有特殊的开发规范(比如特定的内部库或部署流程),你完全可以基于它的框架,自定义一套私有的 Skills。
好的工具不应该给 AI 自由,而应该给 AI 边界。 这或许就是 AI 编程工程化的终极答案。
海航控股去年净利19.8亿元扭亏为盈,四家子公司实现盈利
美国能源部将释放第三批战略石油储备
我国首座海上移动式多功能措施平台“增产一号”交付
Vue 封装 Echarts 组件
为了方便在不同页面使用 echarts,可以封装一个组件。如果不封装,也可以手动实例化 echarts,并且额外处理监听容器尺寸变化的功能。
<script setup lang="ts">
import { useResizeObserver } from "@vueuse/core";
import type { EChartsOption } from "echarts";
import { init, type ECharts, type ECElementEvent } from "echarts/core";
const props = defineProps<{
/** Echarts 图表配置选项 */
options?: EChartsOption;
/** 图表渲染器类型,默认为 svg */
renderer?: "canvas" | "svg";
}>();
const emit = defineEmits<{
chartClick: [event: ECElementEvent];
}>();
/** 图表容器元素的引用 */
const container = useTemplateRef("figure-element");
/** Echarts 图表实例 */
const chart = shallowRef<ECharts>();
defineExpose({
container,
chart,
});
/**
* 监听图表配置变化并更新图表
*/
watchEffect(() => {
if (!chart.value || !props.options) return;
chart.value.setOption(props.options);
});
/**
* 监听容器尺寸变化并自动调整图表大小
*/
useResizeObserver(container, () => {
if (!chart.value || chart.value.isDisposed()) return;
chart.value.resize();
});
/**
* 初始化图表实例
*/
watch(container, (container) => {
if (!container) return;
const instance = init(container, undefined, {
renderer: props.renderer || "svg",
locale: "ZH",
});
/** 绑定图表点击事件 */
instance.on("click", (event) => {
emit("chartClick", event);
});
chart.value = instance;
onWatcherCleanup(() => instance.dispose());
});
</script>
<template>
<figure ref="figure-element" :class="$style.figure" />
</template>
<style module>
.figure {
overflow: hidden;
}
</style>
然后在页面中使用。
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import { BarChart, LineChart, PieChart, ScatterChart } from "echarts/charts";
import {
GridComponent,
LegendComponent,
TitleComponent,
TooltipComponent,
} from "echarts/components";
import { use } from "echarts/core";
import { UniversalTransition } from "echarts/features";
import { SVGRenderer } from "echarts/renderers";
import EchartsContainer from "@/components/Echarts/EchartsContainer.vue";
use([
GridComponent,
LineChart,
BarChart,
SVGRenderer,
PieChart,
ScatterChart,
UniversalTransition,
TitleComponent,
TooltipComponent,
LegendComponent,
]);
/** 基础柱状图配置 */
const barChartOption: EChartsOption = {
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
},
},
xAxis: {
type: "category",
data: ["一月", "二月", "三月", "四月", "五月", "六月"],
axisTick: {
alignWithLabel: true,
},
},
yAxis: {
type: "value",
},
series: [
{
name: "销售额",
type: "bar",
data: [120, 200, 150, 80, 70, 110],
},
],
};
/** 折线图配置 */
const lineChartOption: EChartsOption = {
tooltip: {
trigger: "axis",
},
legend: {
data: ["新用户", "活跃用户"],
},
xAxis: {
type: "category",
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
},
yAxis: {
type: "value",
},
series: [
{
name: "新用户",
type: "line",
data: [120, 132, 101, 134, 90, 230, 210],
smooth: true,
itemStyle: {
color: "#67C23A",
},
},
{
name: "活跃用户",
type: "line",
data: [220, 182, 191, 234, 290, 330, 310],
smooth: true,
itemStyle: {
color: "#E6A23C",
},
},
],
};
/** 饼图配置 */
const pieChartOption: EChartsOption = {
tooltip: {
trigger: "item",
formatter: "{a} <br/>{b}: {c} ({d}%)",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "产品分类",
type: "pie",
radius: "50%",
data: [
{ value: 1048, name: "电子产品" },
{ value: 735, name: "服装配饰" },
{ value: 580, name: "家居用品" },
{ value: 484, name: "食品饮料" },
{ value: 300, name: "其他" },
],
},
],
};
/** 散点图配置 */
const scatterChartOption: EChartsOption = {
tooltip: {
trigger: "item",
},
xAxis: {
type: "value",
name: "X轴",
},
yAxis: {
type: "value",
name: "Y轴",
},
series: [
{
name: "数据点",
type: "scatter",
data: Array.from({ length: 50 }, () => [Math.random() * 100, Math.random() * 100]),
},
],
};
/** 处理图表点击事件 */
const handleChartClick = (chartType: string) => {
ElMessage.info(`点击了${chartType}图表`);
};
</script>
<template>
<div :class="$style.container">
<!-- 柱状图 -->
<EchartsContainer
:class="$style.chart"
:options="barChartOption"
@chart-click="handleChartClick('柱状图')"
/>
<!-- 折线图 -->
<EchartsContainer
:class="$style.chart"
:options="lineChartOption"
@chart-click="handleChartClick('折线图')"
/>
<!-- 饼图 -->
<EchartsContainer
:class="$style.chart"
:options="pieChartOption"
@chart-click="handleChartClick('饼图')"
/>
<!-- 散点图 -->
<EchartsContainer
:class="$style.chart"
:options="scatterChartOption"
@chart-click="handleChartClick('散点图')"
/>
</div>
</template>
<style module>
.container {
padding: 2rem;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.chart {
height: 30rem;
}
</style>
uni-app 运行时揭秘:styleIsolation 的转化
背景
大家好,我是 uni-app 的核心开发 前端笨笨狗。本篇是 uni-app 源码分析的第三篇文章,欢迎关注!
前两天有开发者在群里面问我 uni-app 中如何配置 styleIsolation,我告诉了他正确的配置方案,也计划写篇文章揭秘 uni-app 是如何通过运行时将开发者的配置转化为原生微信小程序的配置。
指南
选项式
在 uni-app 中,开发者可以通过在页面组件中添加 options 配置项来设置 styleIsolation,示例如下:
<script>
export default {
name: 'MyComp',
options: {
styleIsolation: 'isolated'
},
}
</script>
<script>
import { defineComponent } from "vue";
export default defineComponent({
name: "MyComp",
options: {
styleIsolation: "isolated",
},
});
</script>
组合式
在使用组合式 API 的页面组件中,开发者同样可以通过 defineOptions 来设置 styleIsolation,示例如下:
<script setup>
defineOptions({
name: 'MyComp',
options: {
styleIsolation: 'isolated'
}
})
</script>
原理
createComponent 这个函数大家如果看过 vue 文件的 js 编译产物就一定不会陌生,比如
<script setup>
defineOptions({
options: {
styleIsolation: "shared",
},
});
</script>
会被编译为
const _sfc_main = {
__name: "comp",
options: {
styleIsolation: "shared"
}
setup(__props) {
return (_ctx, _cache) => {
return {};
};
}
};
wx.createComponent(_sfc_main);
也就是 script 中写的代码会被编译成一个对象,这个对象就是 vue 组件的配置项,而微信小程序又不认识 vue 组件的配置项,那么怎么把 vue 组件的配置项转化为微信小程序的配置项呢?这就要靠 uni-app 的运行时了,在 common/vendor.js 中,createComponent 函数会调用 parseComponent 函数来解析 vue 组件的配置项,parseComponent 的返回值就是微信小程序组件的配置项,也就是 Component 构造器 的参数,可以用来构造小程序原生组件。
function initCreateComponent() {
return function createComponent(vueComponentOptions) {
return Component(parseComponent(vueComponentOptions));
};
}
const createComponent = initCreateComponent();
wx.createComponent = createComponent;
当 parseComponent 解析到页面组件时,会检查组件的 options 配置项,如果发现 styleIsolation,就会将其转化为微信小程序的配置项。
function parseComponent(vueOptions) {
vueOptions = vueOptions.default || vueOptions;
const options = {
multipleSlots: true,
// styleIsolation: 'apply-shared',
addGlobalClass: true,
pureDataPattern: /^uP$/
};
// 将开发者在 options 中设置的配置项转化为微信小程序的配置项
if (vueOptions.options) {
Object.assign(options, vueOptions.options);
}
const mpComponentOptions = {
options,
// 省略其他配置项
};
return mpComponentOptions;
}
这样一来,开发者在页面组件中设置的 styleIsolation 就会被正确地转化为微信小程序的配置项,从而自由控制样式隔离。
Vue v-html 与 v-text 转 React:VuReact 怎么处理?
VuReact 是一个能将 Vue 3 代码编译为标准、可维护 React 代码的工具。今天就带大家直击核心:Vue 中常见的 v-html/v-text 指令经过 VuReact 编译后会变成什么样的 React 代码?
前置约定
为避免示例代码冗余导致理解偏差,先明确两个小约定:
- 文中 Vue / React 代码均为核心逻辑简写,省略完整组件包裹、无关配置等内容;
- 默认读者已熟悉 Vue 3 中的 v-html 和 v-text 指令用法。
编译对照
v-html:动态 HTML 内容渲染
v-html 是 Vue 中用于将 HTML 字符串动态渲染为 DOM 元素的指令,它会替换元素内的所有内容,并解析 HTML 标签。
- Vue 代码:
<div v-html="htmlContent"></div>
- VuReact 编译后 React 代码:
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
从示例可以看到:Vue 的 v-html 指令被编译为 React 的 dangerouslySetInnerHTML 属性。VuReact 采用 HTML 注入编译策略,将模板指令转换为 React 的特殊属性,完全保持 Vue 的 HTML 渲染语义——将 htmlContent 字符串解析为 HTML 并插入到 DOM 中。
这种编译方式的关键特点在于:
-
语义一致性:完全模拟 Vue
v-html的行为,直接渲染 HTML 字符串 -
安全警告:React 的
dangerouslySetInnerHTML属性名本身就提醒开发者注意 XSS 攻击风险 - 内容替换:与 Vue 一样,会替换元素内的所有现有内容
v-text:纯文本内容渲染
v-text 是 Vue 中用于将纯文本内容设置到元素内的指令,它会替换元素内的所有内容,但不会解析 HTML 标签。
- Vue 代码:
<p v-text="message"></p>
- VuReact 编译后 React 代码:
<p>{message}</p>
从示例可以看到:Vue 的 v-text 指令被编译为 React 的 JSX 插值表达式。VuReact 采用 文本插值编译策略,将模板指令转换为 JSX 的大括号表达式,完全保持 Vue 的文本渲染语义——将 message 作为纯文本内容插入到元素中。
这种编译方式的关键特点在于:
-
语义一致性:完全模拟 Vue
v-text的行为,渲染纯文本内容 - 自动转义:React 的 JSX 插值会自动转义 HTML 特殊字符,防止 XSS 攻击
- 内容替换:与 Vue 一样,会替换元素内的所有现有内容
VuReact 的编译策略确保了从 Vue 到 React 的平滑迁移,开发者无需手动重写内容渲染逻辑。编译后的代码既保持了 Vue 的语义,又符合 React 的安全最佳实践。
🔗 相关资源
- VuReact 官方文档:语义编译对照总览
✨ 如果你觉得本文对你理解 VuReact 有帮助,欢迎点赞、收藏、关注!
iOS 线程常驻(RunLoop 保活)实战:原理、优劣、避坑与双语言实现
作为 iOS 资深开发,线程常驻是底层线程开发的高阶技能,核心用于高频轻量任务、音视频数据流、长连接等极致性能场景。它的本质是通过 RunLoop 保活子线程,让线程执行完任务后不销毁,一直等待新任务。
本文将从核心原理、优劣分析、生产级高级写法、避免方案四个维度深度拆解,并提供 Objective-C + Swift 双语言完整示例。
一、核心原理:线程常驻的底层逻辑
1. 默认线程生命周期
iOS 普通子线程(NSThread/pthread)执行流程:创建线程 → 执行任务 → 任务完成 → 线程自动销毁缺点:频繁创建 / 销毁线程会产生巨大性能开销。
2. 线程常驻核心机制
RunLoop 保活:给子线程绑定一个无限循环的 RunLoop,添加空输入源防止 RunLoop 立即退出,让线程进入休眠状态(不消耗 CPU),实现永久存活。
- 关键 API:
CFRunLoopAddSource(添加保活源)、CFRunLoopRun(启动循环)、CFRunLoopStop(停止循环) - 核心:RunLoop 不退出 → 线程不销毁
3. 适用边界
仅用于高频、轻量、低延迟任务(日志上报、埋点、音视频编解码、长连接心跳);普通业务绝对禁止使用。
二、线程常驻的 优势 VS 劣势(资深视角)
✅ 核心优势
- 极致性能:避免线程频繁创建 / 销毁(线程是操作系统重量级资源,创建耗时≈100ms)
- 低延迟响应:任务直达常驻线程,无线程创建耗时
- 资源可控:专用线程处理特定任务,不与业务线程竞争
- 长连接保活:网络长连接、音视频流必须用常驻线程保证链路不中断
❌ 致命劣势
- 内存泄漏风险:忘记停止 RunLoop → 线程永久驻留内存,无法释放
- 系统资源浪费:常驻线程会占用系统线程池配额,过多会导致 APP 卡顿
- 维护成本极高:手动管理 RunLoop、线程安全、生命周期,极易出现死锁 / 野指针
- 违背系统设计:GCD/NSOperation 已自动实现线程复用,手动常驻是兜底方案
三、线程常驻 高级写法(生产级封装)
基础版仅用于理解原理,工程中必须用高级封装版:单例复用、线程安全任务队列、优雅退出、无内存泄漏。线程常驻仅支持
NSThread(pthread),GCD 无法手动实现常驻(系统自动管理线程)。
方案 1:Objective-C 高级常驻线程
objectivec
#import <Foundation/Foundation.h>
@interface ResidentThread : NSObject
/// 单例全局常驻线程
+ (instancetype)sharedThread;
/// 异步执行任务
- (void)executeTask:(dispatch_block_t)task;
/// 优雅退出线程(必须调用,防止内存泄漏)
- (void)stopThread;
@end
// ====================== 实现 ======================
#import "ResidentThread.h"
@interface ResidentThread ()
@property (nonatomic, strong) NSThread *residentThread; // 常驻线程
@property (nonatomic, assign) BOOL isStopped; // 退出标记
@property (nonatomic, strong) NSLock *lock; // 线程安全锁
@property (nonatomic, strong) NSMutableArray *taskArray; // 任务队列
@end
@implementation ResidentThread
+ (instancetype)sharedThread {
static ResidentThread *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
_isStopped = NO;
_lock = [[NSLock alloc] init];
_taskArray = [NSMutableArray array];
// 创建常驻线程
__weak typeof(self) weakSelf = self;
self.residentThread = [[NSThread alloc] initWithTarget:weakSelf selector:@selector(runLoopAction) object:nil];
self.residentThread.name = @"com.app.resident.thread";
[self.residentThread start];
}
return self;
}
/// RunLoop 保活核心方法
- (void)runLoopAction {
@autoreleasepool {
// 1. 添加空输入源,防止RunLoop立即退出
CFRunLoopSourceContext context = {0};
CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
// 2. 启动RunLoop循环(休眠状态,不消耗CPU)
while (!self.isStopped) {
// 执行队列中的任务
[self.lock lock];
if (self.taskArray.count > 0) {
dispatch_block_t task = self.taskArray.firstObject;
[self.taskArray removeObjectAtIndex:0];
task();
}
[self.lock unlock];
// RunLoop 运行1秒,循环检测
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, NO);
}
// 3. 停止RunLoop,线程销毁
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
NSLog(@"常驻线程已销毁");
}
}
/// 异步添加任务
- (void)executeTask:(dispatch_block_t)task {
if (!task || self.isStopped) return;
[self.lock lock];
[self.taskArray addObject:task];
[self.lock unlock];
}
/// 优雅退出
- (void)stopThread {
if (self.isStopped) return;
self.isStopped = YES;
// 停止RunLoop
CFRunLoopStop(CFRunLoopGetCurrent());
self.residentThread = nil;
}
@end
方案 2:Swift 高级常驻线程
swift
import Foundation
final class ResidentThread {
// 单例
static let shared = ResidentThread()
private init() {
self.setupThread()
}
// MARK: - 私有属性
private var thread: Thread!
private var isStopped = false
private let lock = NSLock()
private var taskArray = [() -> Void]()
// MARK: - 初始化常驻线程
private func setupThread() {
thread = Thread(target: self, selector: #selector(runLoopAction), object: nil)
thread.name = "com.app.resident.thread.swift"
thread.start()
}
// MARK: - RunLoop 保活核心
@objc private func runLoopAction() {
autoreleasepool {
// 1. 添加空源,防止RunLoop退出
let context = CFRunLoopSourceContext()
let source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, context)
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, .defaultMode)
// 2. 循环执行任务
while !isStopped {
lock.lock()
if !taskArray.isEmpty {
let task = taskArray.removeFirst()
task()
}
lock.unlock()
// RunLoop 休眠1秒,低功耗
CFRunLoopRunInMode(.defaultMode, 1.0, false)
}
// 3. 清理资源
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, .defaultMode)
print("Swift 常驻线程已销毁")
}
}
// MARK: - 公开API
/// 执行任务
func execute(task: @escaping () -> Void) {
guard !isStopped else { return }
lock.lock()
taskArray.append(task)
lock.unlock()
}
/// 优雅退出
func stop() {
guard !isStopped else { return }
isStopped = true
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
双语言使用示例
objectivec
// OC 使用
- (void)testResidentThread {
// 执行任务
[[ResidentThread sharedThread] executeTask:^{
NSLog(@"OC 常驻线程执行任务:%@", [NSThread currentThread]);
}];
// 页面销毁/模块销毁时,必须调用退出!
// [[ResidentThread sharedThread] stopThread];
}
swift
// Swift 使用
func testResidentThread() {
// 执行任务
ResidentThread.shared.execute {
print("Swift 常驻线程执行任务:Thread.current)")
}
// 必须在合适时机退出
// ResidentThread.shared.stop()
}
四、如何避免线程常驻?(最优工程实践)
99% 的业务场景,完全不需要手动实现线程常驻!苹果的 GCD / NSOperation 已经内置了线程池复用机制,系统自动管理线程生命周期,比手动常驻更安全、更高效。
替代方案 1:GCD 串行队列(系统自动复用线程)
GCD 会复用空闲线程,不会频繁创建 / 销毁,完美替代手动常驻线程。
objectivec
// OC:GCD 复用线程(推荐)
dispatch_queue_t serialQueue = dispatch_queue_create("com.app.gcd.serial", DISPATCH_QUEUE_SERIAL);
- (void)gcdTask {
dispatch_async(serialQueue, ^{
NSLog(@"GCD 复用线程:%@", [NSThread currentThread]);
});
}
swift
// Swift:GCD 复用线程
private let serialQueue = DispatchQueue(label: "com.app.gcd.serial.swift")
func gcdTask() {
serialQueue.async {
print("GCD 复用线程:Thread.current)")
}
}
替代方案 2:NSOperationQueue(可控并发)
swift
// Swift 操作队列
private let operationQueue = OperationQueue()
init() {
operationQueue.maxConcurrentOperationCount = 1 // 串行复用
}
func operationTask() {
let op = BlockOperation {
print("NSOperation 复用线程")
}
operationQueue.addOperation(op)
}
避免线程常驻的核心原则
- 普通业务 → 用 GCD:系统自动线程复用,零维护成本
- 复杂任务 → 用 NSOperation:支持依赖 / 取消,自动管理线程
- 绝对禁止:无理由创建手动常驻线程
- 必须用常驻:仅音视频、长连接、低延迟心跳等极致场景
五、关键避坑指南
-
必须优雅退出:页面 / 模块销毁时,一定要调用
stopThread停止 RunLoop,否则内存泄漏 - 禁止多开:整个 APP 最多创建 1~2 个 常驻线程,过多会耗尽系统线程资源
- 线程安全:任务队列必须加锁,防止多线程读写崩溃
- 禁止 UI 操作:常驻线程是子线程,绝对不能更新 UI
-
低功耗设计:RunLoop 使用
RunInMode定时休眠,不要无限循环消耗 CPU
总结
- 核心原理:线程常驻 = RunLoop 保活,是底层性能优化方案
- 高级写法:生产级必须封装单例 + 线程安全队列 + 优雅退出
- 优劣:性能极致但风险极高,仅用于特殊场景
- 最优解:优先用 GCD/NSOperation,系统自动线程复用,避免手动常驻
- 生命周期:常驻线程必须手动退出,否则永久泄漏