【共创稿事节】碰哪传哪,坐标即地址:把 HarmonyOS 7「碰一碰」搬上鸿蒙 PC——Electron 40 实战 TapRipple 触涟
【共创稿事节】碰哪传哪,坐标即地址:把 HarmonyOS 7「碰一碰」搬上鸿蒙 PC——Electron 40 实战 TapRipple 触涟
本文是 HarmonyOS PC 开发实践系列之一,聚焦 HarmonyOS 7「能力二:碰一碰 · 精准分享」,完整演示如何用 Electron 40(鸿蒙 CPF-Electron v40.0.1 运行时) 把一个「碰哪传哪」的交互体验真正跑在 鸿蒙 PC 电脑 上。文中所有代码均来自可运行工程,文末附 真机截图、验证命令 与 踩坑清单。

前言
过去十年,我们习惯了「分享给应用」——把一张图拖进微信,再让对方自己去找。HarmonyOS 7 把碰一碰能力做了一次关键升级:手机轻触 PC / 平板屏幕时,系统能拿到 触点坐标,于是分享的粒度从「应用」细化到了「坐标」。内容可以定向直达光标、直达图纸上的某个标注点、直达影像墙的下一格。
这听起来只是一次 API 升级,但落到交互设计上,它彻底改变了「投递」这件事的心智模型:不再是"发给我" ,而是"发到这里"。我给这个体验起了个名字——触涟(TapRipple):手机落点像一颗石子入水,涟漪扩散,内容顺着涟漪的方向被精准送达。
而这一切,要跑在 鸿蒙 PC 上。这意味着我们不能用 npm 上那个标准 Electron,而要跑在鸿蒙 HAP 壳内嵌的 libelectron.so 里。本文就把这条链路从头拆到尾。
关键词:鸿蒙 PC、HarmonyOS 7、碰一碰、精准分享、触点坐标、Electron 40、CPF-Electron、libelectron.so、HAP、定向投递
一、能力解读:从「分享给应用」到「分享给坐标」
先把这个能力讲清楚,因为它是整个工程的地基。
| 传统分享 | HarmonyOS 7 碰一碰精准分享 |
|---|---|
| 选内容 → 选应用 → 应用决定落在哪 | 选内容 → 轻触屏幕 → 系统把触点坐标交给目标窗口 |
| 落点是"应用内部逻辑" | 落点是"屏幕上的一个点" |
| 无法精准定位到光标/图元/格子 | 可直达光标位置、可吸附标注锚点、可落格追加 |
所以在 PC 上,同一个内容碰到不同窗口,应该产生完全不同的投递行为:
- 碰到 图纸板:现场照片 吸附挂载到最近的测量标注点;
- 碰到 文稿台:原图/图表 直达光标位置,光标旁即时插入;
- 碰到 影像墙:内容 落格追加到下一格;
- 碰到 纪要板:语音便签 转写落行。
TapRipple 把这条链路做成一间可视化的「深海信号台」:左侧手机托盘选中载荷,中央四扇目标窗口,右侧信号日志留痕。碰哪,传哪,落空也有涟漪。

二、工程骨架:Electron 40 如何跑在鸿蒙 PC 上
2.1 关键前提:不是标准 Electron
这是所有鸿蒙 PC Electron 工程的第一课:
- npm 上的标准 Electron 二进制 无法在 OpenHarmony 上运行;
- 业务代码实际运行在 HAP 壳内嵌的
libelectron.so(v40.0.1-release)里; - 因此工程 零 npm 依赖,一切用原生 Web + Node 标准库完成。
工程结构如下(scripts/check.mjs 会强制校验这些约束):
TapRipple/
├── app/ # 业务层(主进程 + 渲染层 + 纯函数引擎)
│ ├── main.js # 主进程:窗口、安全基线、IPC
│ ├── main-utils.cjs # 触点夹取 / 运行时信息 / 可信来源校验
│ ├── preload.js # contextBridge 暴露 window.tapripple
│ ├── tapshare.mjs # 纯函数引擎:命中/吸附/投递/涟漪
│ ├── renderer.mjs # 渲染层交互编排
│ ├── index.html # 单页结构 + CSP 基线
│ └── styles.css # 深海信号台视觉
├── scripts/ # check/build/doctor + hap 流水线
├── tests/ # node:test 单测(引擎 + 主进程工具)
└── hap.config.json # 包名 / 模块名 / SDK 分支集中配置
2.2 主进程:鸿蒙 PC 的三条硬约束
主进程 app/main.js 里有三行代码,是鸿蒙 PC 上「不写就翻车」的:
'use strict';
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const { app, BrowserWindow, ipcMain, Menu, session } = require('electron');
const { clampTouchPoint, getRuntimeInfo, isTrustedUrl } = require('./main-utils.cjs');
const indexPath = path.join(__dirname, 'index.html');
let mainWindow = null;
// ① 鸿蒙 PC 上 platform 实测返回 'openharmony',也见过 'ohos',两个都要认
const isOhos = process.platform === 'ohos' || process.platform === 'openharmony';
app.setName('TapRipple');
function createWindow() {
mainWindow = new BrowserWindow({
title: 'TapRipple · 触涟',
width: 1560,
height: 980,
minWidth: 720,
minHeight: 560,
backgroundColor: '#06141d',
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
// ② 安全基线:开隔离、关 node、禁不安全内容
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
webSecurity: true,
allowRunningInsecureContent: false
}
});
mainWindow.once('ready-to-show', () => {
mainWindow?.show();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.loadFile(indexPath).catch((error) => {
console.error('[tapripple] loadFile 失败:', error.message);
mainWindow?.loadURL(pathToFileURL(indexPath).href);
});
}
然后是第三条,也是鸿蒙 PC 最容易被忽略的一条:
// ③ 鸿蒙 PC 窗口自带系统菜单区,应用内菜单必须置空,否则叠成两层
Menu.setApplicationMenu(null);
为什么必须置空?因为鸿蒙 PC 的窗口本身已经带了系统菜单区(就是截图左上角那条「项目 / 产品信息 / 签名配置 / 编译选项」的区域),如果应用再画一层 Electron 菜单,就变成上下两层菜单,视觉直接崩掉。Menu.setApplicationMenu(null) 不是可选优化,是鸿蒙 PC 的硬性要求。
主进程还顺手做了两件安全事:拒绝一切权限请求、拦截一切外部导航。
app.on('web-contents-created', (_event, contents) => {
contents.setWindowOpenHandler(() => ({ action: 'deny' }));
contents.on('will-navigate', (event, navigationUrl) => {
if (!isTrustedUrl(navigationUrl, indexPath)) {
event.preventDefault();
}
});
});
app.whenReady().then(() => {
session.defaultSession.setPermissionRequestHandler((_webContents, _permission, callback) => {
callback(false);
});
// ... IPC 注册与窗口创建
Menu.setApplicationMenu(null);
createWindow();
});
2.3 preload:只暴露两个最小接口
contextIsolation: true 下,渲染层拿不到 Node,只能通过 contextBridge 拿到白名单能力。TouchRipple 只暴露两个方法,一个读运行时、一个校准触点:
'use strict';
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('tapripple', {
getRuntime: () => ipcRenderer.invoke('runtime:get'),
calibrateTouch: (point) => ipcRenderer.invoke('touch:calibrate', point)
});
小细节:主进程还必须同时识别
'openharmony'和'ohos'两个 platform 返回值——不同鸿蒙 PC 版本实测返回过两个值,少认一个就会出现「平台识别为浏览器预览」的尴尬。scripts/check.mjs会强制校验这一点,漏写直接构建失败。
三、纯函数引擎:把「触点 → 投递」拆成可单测的语义
整个交互最怕什么?怕逻辑和 UI 搅在一起,动一下动效就改坏一次命中判定。所以我把所有「决策类」逻辑抽成 app/tapshare.mjs,零 DOM、零 Electron、纯函数,渲染层和单测共用同一套语义。
3.1 载荷与目标:两套枚举
export const CONTENT_KINDS = Object.freeze({
ORIGINAL_PHOTO: { kind: 'original-photo', label: '原图', payloadMB: 12.5 },
FIELD_PHOTO: { kind: 'field-photo', label: '现场照片', payloadMB: 4.2 },
CHART_DATA: { kind: 'chart-data', label: '图表数据', payloadMB: 0.3 },
VOICE_MEMO: { kind: 'voice-memo', label: '语音便签', payloadMB: 1.8 }
});
export const TARGET_KINDS = Object.freeze({
BLUEPRINT: { kind: 'blueprint', label: '图纸板', hint: '挂载现场照片' },
SLIDES: { kind: 'slides', label: '文稿台', hint: '原图直达光标' },
GALLERY: { kind: 'gallery', label: '影像墙', hint: '落格追加' },
MEMOPAD: { kind: 'memopad', label: '纪要板', hint: '语音转写落点' }
});
3.2 触点归一化:先把坐标按死
手机上报的坐标必须先夹到画布范围,否则一次越界坐标就能把后面整条链路带崩:
export function normalizePoint(point, bounds) {
const x = Number(point?.x);
const y = Number(point?.y);
if (!Number.isFinite(x) || !Number.isFinite(y) || !bounds) {
return null;
}
const width = Math.max(1, Number(bounds.width) || 0);
const height = Math.max(1, Number(bounds.height) || 0);
return {
x: Math.min(Math.max(x, 0), width),
y: Math.min(Math.max(y, 0), height)
};
}
3.3 命中判定:返回最近窗口,落空也算结果
命中不是简单的"点在矩形内",而是 “找离触点最近的那扇窗,并告诉你有没有落在里面”。这样即使碰偏了,也能给最近的窗口一个"未命中"的反馈,而不是静默丢弃:
// 触点命中:返回最近的可达目标;超出 TOUCH_RADIUS 视为落空(涟漪仍会扩散)
export function hitTest(targets, point) {
if (!Array.isArray(targets) || targets.length === 0 || !point) {
return null;
}
let best = null;
for (const target of targets) {
const rect = target.rect;
if (!rect) {
continue;
}
const within = point.x >= rect.x && point.x <= rect.x + rect.width
&& point.y >= rect.y && point.y <= rect.y + rect.height;
const cx = rect.x + rect.width / 2;
const cy = rect.y + rect.height / 2;
const distance = Math.hypot(point.x - cx, point.y - cy);
if (!best || distance < best.distance) {
best = { target, within, distance, center: { x: cx, y: cy } };
}
}
return best;
}
3.4 锚点吸附:图纸板的"磁性"
图纸板上预置了 3 个测量标注点。碰点只要离某个标注点 72px 以内,就自动吸附过去——这就是"挂载现场照片"的落点语义:
// 锚点吸附:图纸板上的测量点/标注点,碰点吸附最近锚
export function snapAnchor(anchors, point, maxDistance = 72) {
if (!Array.isArray(anchors) || anchors.length === 0 || !point) {
return null;
}
let best = null;
for (const anchor of anchors) {
const distance = Math.hypot(point.x - anchor.x, point.y - anchor.y);
if (!best || distance < best.distance) {
best = { anchor, distance };
}
}
if (!best || best.distance > maxDistance) {
return null;
}
return best;
}
3.5 投递矩阵:不同目标 × 不同内容 = 不同策略
这是整个引擎的"大脑"——一张 内容 × 目标 的投递矩阵,命中后查表得到投递模式:
const DELIVERY_MATRIX = Object.freeze({
'original-photo': {
slides: { mode: 'cursor-drop', label: '原图投递到光标' },
gallery: { mode: 'grid-append', label: '原图入墙落格' },
blueprint: { mode: 'anchor-mount', label: '原图挂载标注点' },
memopad: { mode: 'transcript-insert', label: '原图插入纪要' }
},
'field-photo': {
blueprint: { mode: 'anchor-mount', label: '现场照片挂载锚点' },
slides: { mode: 'cursor-drop', label: '现场照片落到光标' },
gallery: { mode: 'grid-append', label: '现场照片入墙' },
memopad: { mode: 'transcript-insert', label: '现场照片插入纪要' }
},
// ... 图表数据 / 语音便签 同理
});
export function resolveDelivery(contentKind, targetKind) {
const row = DELIVERY_MATRIX[contentKind];
if (!row || !row[targetKind]) {
return { mode: 'rejected', label: '该目标暂不接收此类内容' };
}
return row[targetKind];
}
3.6 投递速率分档 + 涟漪时序 + 飞卡轨迹
不同「目标 × 内容」组合配不同传输速率,光标直达最快(86MB/s)。涟漪用三段错峰扩散,飞卡用二次贝塞尔拱线——这三段都是纯数学,天然可测:
export function deliverySpeedMB(payloadMB, mode) {
const size = Number(payloadMB);
if (!Number.isFinite(size) || size < 0) {
return 0;
}
const rates = { 'cursor-drop': 86, 'anchor-mount': 64, 'grid-append': 58, 'transcript-insert': 42, rejected: 0 };
const rate = rates[mode] ?? 50;
return Math.round(size * rate * 10) / 10;
}
// 涟漪时序:t 归一化 0..1,返回三圈涟漪的半径比例与透明度
export function ripplePhases(t) {
const time = Math.min(Math.max(Number(t) || 0, 0), 1);
const rings = [];
for (let i = 0; i < 3; i += 1) {
const local = Math.min(Math.max((time - i * 0.18) / 0.64, 0), 1);
rings.push({
scale: 0.16 + local * 1.84,
alpha: local > 0 ? Math.max(0, 1 - local) * (1 - i * 0.22) : 0
});
}
return rings;
}
// 卡片飞行轨迹:二次贝塞尔,t 归一化 0..1
export function driftPath(from, to, t) {
const time = Math.min(Math.max(Number(t) || 0, 0), 1);
if (!from || !to) {
return null;
}
const control = {
x: (from.x + to.x) / 2,
y: Math.min(from.y, to.y) - Math.abs(to.x - from.x) * 0.18 - 48
};
const invert = 1 - time;
return {
x: invert * invert * from.x + 2 * invert * time * control.x + time * time * to.x,
y: invert * invert * from.y + 2 * invert * time * control.y + time * time * to.y,
progress: time
};
}
为什么坚持把涟漪、飞卡也写成纯函数?因为动效的"手感"也可以被单元测试锁住——半径比例、透明度衰减、贝塞尔轨迹,全都能在
node --test里断言。动效不是玄学,是可回归的数学。
四、渲染层接线:涟漪、飞卡、锚点、台账
渲染层 app/renderer.mjs 只做一件事:把引擎的"决策"翻译成 DOM 动作。它不重新实现任何判定逻辑。
4.1 一次触碰的完整生命周期
onDeskTap 是主入口,把「取点 → 归一 → 校准 → 命中 → 分支 → 留痕」串成一条流水线:
async function onDeskTap(event) {
if (state.busy) {
return;
}
const { x, y, rect } = deskPoint(event);
const raw = normalizePoint({ x, y }, { width: rect.width, height: rect.height });
if (!raw) {
return;
}
let point = raw;
if (bridge) {
try {
const calibrated = await bridge.calibrateTouch(raw);
if (calibrated?.ok && calibrated.point) {
point = calibrated.point;
}
} catch {
point = raw;
}
}
state.busy = true;
const meta = CONTENT_KINDS[state.content];
const hit = hitTest(targetRects(), point);
const miss = !hit?.within;
spawnRipple(point, miss);
if (miss || !hit) {
// 落空也要留痕,防误触心理预期
const entry = recordDelivery(state.ledger, {
contentKind: meta.kind,
targetKind: 'none',
mode: 'missed',
label: '落空涟漪:未触到任何窗口',
point, mb: 0, atMs: Date.now()
});
updateLedger(entry, true);
showTouchCue(point, '涟漪落空,未命中任何目标窗口');
state.busy = false;
return;
}
// ... 命中分支见下
}
4.2 涟漪:requestAnimationFrame 驱动三圈扩散
function spawnRipple(point, miss) {
const holder = document.createElement('div');
holder.className = `ripple${miss ? ' miss' : ''}`;
holder.style.left = `${point.x}px`;
holder.style.top = `${point.y}px`;
els.desk.appendChild(holder);
const start = performance.now();
const duration = 980;
function frame(now) {
const t = (now - start) / duration;
if (t >= 1) {
holder.remove();
return;
}
const first = ripplePhases(t)[0];
holder.style.transform = `scale(${first.scale})`;
holder.style.opacity = String(first.alpha);
holder.style.boxShadow = `0 0 ${Math.round(28 * first.scale)}px rgba(45, 226, 195, ${first.alpha * 0.5})`;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
4.3 命中分支:把策略落到四个窗口
命中后按 strategy.mode 分发到不同窗口的"落点动作",这就是四种投递语义的真实落地:
function applyEffect(mode, target, point, meta) {
if (mode === 'cursor-drop') {
if (target === 'slides') {
els.slideFigure.textContent = `▲ 已在光标处插入:${meta.label}(${meta.payloadMB} MB)`;
els.caret.before(document.createTextNode(`〔${meta.label}〕`));
}
return;
}
if (mode === 'anchor-mount') {
const snapped = snapAnchor(anchorPoints(), point);
const chosen = snapped?.anchor ?? anchorPoints()[0];
if (chosen) {
const dot = state.anchors[chosen.index]?.element;
if (dot) {
dot.classList.add('mounted'); // 锚点点亮
dot.title = `${meta.label} · 已挂载`;
}
}
return;
}
if (mode === 'grid-append') {
const cells = [...els.galleryGrid.children];
const cell = cells[state.galleryIndex % cells.length];
state.galleryIndex += 1;
cell.classList.add('filled'); // 落格追加
cell.textContent = meta.label.slice(0, 2);
return;
}
if (mode === 'transcript-insert') {
state.memoCount += 1;
const line = document.createElement('div');
line.className = 'memo-line new';
line.textContent = `${String(state.memoCount).padStart(2, '0')} · ${meta.label}已转写归档`;
els.memoLines.prepend(line); // 转写落行
}
}
4.4 台账:40 条环形留痕 + 三项统计
每一次投递(含落空)都进日志,只保留最近 40 条,并同步刷新「投递 / 落空 / 累计 MB」三项统计:
function updateLedger(entry, miss) {
const item = document.createElement('li');
item.textContent = formatLedgerEntry(entry, kindLabels());
if (miss) {
item.classList.add('miss');
}
els.ledgerList.prepend(item);
while (els.ledgerList.children.length > 40) {
els.ledgerList.lastChild.remove();
}
const entries = state.ledger.entries;
els.statCount.textContent = String(entries.filter((e) => e.mode !== 'rejected' && e.mode !== 'missed').length);
els.statMiss.textContent = String(entries.filter((e) => e.mode === 'rejected' || e.mode === 'missed').length);
els.statTraffic.textContent = String(Math.round(entries.reduce((sum, e) => sum + (e.mb || 0), 0)));
}
五、主进程 IPC:触点坐标必须"夹取"
渲染层算出的坐标不能直接信——尤其在鸿蒙 PC 上,触点由手机侧上报,越界、非数字、脏数据都可能出现。所以在主进程加了一道 clampTouchPoint 守卫,所有进入投递链的坐标都要过这道闸:
'use strict';
const TOUCH_LIMITS = { maxX: 4096, maxY: 4096 };
// 触点坐标夹取:碰一碰上报的坐标必须落在有效屏幕区域内
function clampTouchPoint(point, limits = TOUCH_LIMITS) {
const x = Math.round(Number(point?.x));
const y = Math.round(Number(point?.y));
if (!Number.isFinite(x) || !Number.isFinite(y)) {
return null;
}
if (x < 0 || y < 0 || x > limits.maxX || y > limits.maxY) {
return null;
}
return { x, y };
}
主进程把它挂成 IPC handler,且做了 可信来源校验——只有来自本应用 index.html 的调用才放行:
function assertTrustedSender(event) {
if (!isTrustedUrl(event.senderFrame?.url, indexPath)) {
throw new Error('Untrusted IPC sender');
}
}
ipcMain.handle('runtime:get', (event) => {
assertTrustedSender(event);
return getRuntimeInfo(app, process);
});
// 碰一碰触点校准:渲染层把屏幕触点送来夹取,防止越界坐标进入投递链
ipcMain.handle('touch:calibrate', (event, point) => {
assertTrustedSender(event);
const clamped = clampTouchPoint(point);
return { ok: Boolean(clamped), point: clamped };
});
可信来源校验本身也很好写——只认 file: 协议且路径与 index.html 完全一致:
function isTrustedUrl(candidate, indexPath) {
if (!candidate) {
return false;
}
try {
const url = new URL(candidate);
const trusted = pathToFileURL(indexPath);
return url.protocol === 'file:' && url.origin === trusted.origin && url.pathname === trusted.pathname;
} catch {
return false;
}
}
runtime:get 则把运行时信息带回来,让右上角徽章能诚实地显示「鸿蒙 PC / 浏览器预览」:
function getRuntimeInfo(electronApp, runtimeProcess) {
const systemVersion = typeof runtimeProcess.getSystemVersion === 'function'
? runtimeProcess.getSystemVersion()
: 'unknown';
return {
name: electronApp.getName(),
version: electronApp.getVersion(),
platform: runtimeProcess.platform, // 'openharmony' / 'ohos' / 'browser-preview'
architecture: runtimeProcess.arch,
systemVersion,
electron: runtimeProcess.versions.electron || 'unknown',
chromium: runtimeProcess.versions.chrome || 'unknown',
node: runtimeProcess.versions.node || 'unknown'
};
}
六、视觉与动效:一间深海信号台
视觉上我没有沿用常见的浅色工具面板,而是做了一间 深海墨青 + 电光青霓虹 的信号台。配色直接写在 CSS 变量里,一眼能看出"信号/电波"的调性:
:root {
color-scheme: dark;
--abyss: #06141d; /* 深海底 */
--abyss-2: #0a2230;
--ink: #d9f1ef;
--dim: #7fa8ab;
--neon: #2de2c3; /* 电光青 */
--neon-2: #37b6ff; /* 信号蓝 */
--coral: #ff7a66; /* 落空珊瑚 */
--gold: #ffc76b;
--glass: rgba(21, 52, 66, 0.62);
--line: rgba(45, 226, 195, 0.22);
--radius: 18px;
font-size: 17px; /* 正文基准 17px,适合长时间阅读 */
}
三栏布局:手机托盘(左)→ 碰一碰台(中)→ 信号日志(右)。中央画布上四扇目标窗口默认带尺寸、带锚点、带网格,用户一眼就知道"能碰哪、碰了会发生什么"。
下图为鸿蒙 PC 上的真实运行画面(背景是 DevEco Studio,右上角徽章显示 TapRipple 0.1.0 · 鸿蒙 PC · Electron v40.0.1-release),此时选中「原图」,速率预估待命中:

选中不同载荷,左下角「分享速率预估」会实时变化,这就是 3.6 节 deliverySpeedMB 在界面上的直接映射。三张实拍分别是现场照片、图表数据、语音便签:



四张截图对应 cursor-drop 通道(86MB/s)的预估速率,正好可以用一张表把「载荷大小 → 速率」的关系讲清楚:
| 载荷 | 大小 | 速率预估(cursor-drop 86MB/s) | 界面读数 |
|---|---|---|---|
| 原图 | 12.5 MB | 12.5 × 86 = 1075 MB/s | 待命中 |
| 现场照片 | 4.2 MB | 4.2 × 86 = 361.2 MB/s | 361.2 MB/s |
| 图表数据 | 0.3 MB | 0.3 × 86 = 25.8 MB/s | 25.8 MB/s |
| 语音便签 | 1.8 MB | 1.8 × 86 = 154.8 MB/s | 154.8 MB/s |
速率不是随便写的常数,而是
deliverySpeedMB里cursor-drop: 86这条真实映射的分类结果。界面上的每个数字,都能在引擎里找到出处,这是我做这类演示工程的一条底线。
底部状态栏还会实时显示 本机时间 · 感应半径 96px——TOUCH_RADIUS 直接来自引擎常量,改一处全链路生效。
七、真机验证:在鸿蒙 PC 上把它跑起来
光在浏览器里跑通不算数,必须上鸿蒙 PC 真机。工程提供了一套 verify + hap 流水线,命令都在 package.json 里:
{
"scripts": {
"icons": "node scripts/make-icons.mjs",
"build": "node scripts/build.mjs",
"check": "node scripts/check.mjs",
"test": "node --test tests/*.test.mjs",
"verify": "npm run check && npm test && npm run build",
"doctor": "node scripts/doctor.mjs",
"hap:init": "node scripts/hap-init.mjs",
"hap:relink": "node scripts/hap-relink.mjs",
"hap:sync": "node scripts/hap-sync.mjs",
"hap:sign": "node scripts/hap-sign.mjs",
"hap:build": "npm run hap:sync && sh scripts/hap-build.sh",
"hap:install": "sh scripts/hap-install.sh",
"hap:start": "sh scripts/hap-start.sh",
"hap:dev": "npm run hap:build && npm run hap:install && npm run hap:start"
}
}
7.1 三道本地关卡
npm run check # 静态体检:语法 + 安全基线 + 鸿蒙平台约束
npm test # 单测:引擎纯函数 + 主进程工具
npm run build # 构建 dist 业务包
# 一条命令跑完三道关
npm run verify
check.mjs 会逐条校验:CSP 含 script-src 'self' / object-src 'none'、主进程含 contextIsolation: true 等四项安全配置、含 Menu.setApplicationMenu(null)、同时识别 'openharmony' 与 'ohos'、且禁止出现 npm 标准 electron 依赖。等于是把"鸿蒙 PC 会不会翻车"提前在 CI 里拦住了。
7.2 上屏五步
npm run hap:init # 从官方 v40.0.1 预编译包生成 HAP 壳(不入库)
npm run hap:sign # 复用 ~/.ohos/config 签名材料(包名随材料切换)
npm run hap:build # node hvigorw.js assembleHap
npm run hap:install # hdc install -r(成功判据:输出含 install bundle successfully)
npm run hap:start # aa start 拉起 EntryAbility
几个只看退出码会被坑的点:hdc install 的成功判据是输出文本包含 install bundle successfully,而不是退出码为 0;node hvigorw.js 这类构建在鸿蒙 PC 上有时会出现 WARN 导致退出码非零,但产物其实已生成——一定要看 BUILD SUCCESSFUL 字样。
7.3 包名与安装冲突
hap.config.json 里把包名集中管理,实测值为 com.nexaport.app,模块名 electron,SDK 分支 v40.0.1:
{
"bundleName": "com.nexaport.app",
"moduleName": "electron",
"abilityName": "EntryAbility",
"productName": "default",
"sdkBranch": "v40.0.1",
"runtimeDirectory": "web_engine/src/main/resources/resfile/resources",
"hmosCltHome": "/data/service/hnp/hmos-clt.org/hmos-clt_1.0.0"
}
注意:包名以
hap:sign的结果为准。签名材料(.p7b/.p12/.cer与配套密文)把包名、证书、profile 三者绑死,换材料包名就会跟着切。多工程共用同一设备时,务必让每个工程bundleName错开,否则会互相覆盖安装;如果versionCode更低的包去install -r,会被鸿蒙直接拒绝,得先uninstall。
7.4 浏览器预览兜底
没连设备时,直接双击 app/index.html 就能完整体验——因为渲染层对 window.tapripple 做了优雅降级:拿不到桥就用 browser-preview 兜底,全部交互(选载荷、触碰、涟漪、飞卡、台账)照常工作,只是顶部徽章会诚实显示"浏览器预览"。
function loadRuntime() {
if (!bridge) {
renderRuntime({ name: 'TapRipple', version: '0.1.0', platform: 'browser-preview', electron: 'browser' });
return;
}
bridge.getRuntime().then(renderRuntime).catch(() => {
renderRuntime({ name: 'TapRipple', version: '0.1.0', platform: 'browser-preview', electron: 'browser' });
});
}
“降级但可用” 是我给这套演示工程定的第二底线:任何时候,都不能让评审/读者因为没设备而看不到东西。
八、踩坑清单(鸿蒙 PC 实测)
Menu.setApplicationMenu(null)不能省:鸿蒙 PC 窗口自带系统菜单区,应用菜单会叠成两层,视觉直接崩。check.mjs已把它列为一票否决项。- platform 要认两个值:
'openharmony'与'ohos'都出现过,少认一个就会误判为浏览器预览。 - 别装 npm 标准 Electron:OpenHarmony 无官方二进制,业务代码跑在 HAP 内
libelectron.so,工程必须零 npm electron 依赖。 hdc install看文本不看码:成功判据是输出含install bundle successfully;hvigor出现 WARN 时退出码可能非零,但BUILD SUCCESSFUL即成功。- 包名随签名材料走:
.p7b把包名、证书、密文三者绑定,换材料包名就切;多工程务必错开bundleName,否则互相覆盖,低versionCode的install -r会被拒。 - 触点必须夹取:手机上报的坐标可能越界/非数字,
clampTouchPoint这道闸不能省,否则一次脏数据就能让后续整条投递链报错。 - 锚点用百分比而非像素:图纸板锚点写
left: 30%; top: 42%,窗口形变时自动重排,不用监听 resize 重算坐标。 - 动效写成纯函数:涟漪时序、飞卡轨迹都抽进引擎,
node --test可直接断言,避免"改个动效改坏命中"。
九、总结
把「碰一碰 · 精准分享」搬上鸿蒙 PC,表面看是"做个动效",实际是一次完整的能力落地演练:
- 对能力:触点坐标是新的"地址系统",让分享粒度从应用细化到坐标;
- 对架构:纯函数引擎(
tapshare.mjs)+ 渲染层接线(renderer.mjs)+ 主进程守卫(main-utils.cjs)三层解耦,决策可测、动效可回归; - 对平台:
Menu.setApplicationMenu(null)、双 platform 识别、零 npm electron 依赖、CSP 与安全基线,是鸿蒙 PC Electron 的四块"地基石"; - 对体验:深海信号台的三栏布局 + 三圈涟漪 + 贝塞尔飞卡 + 落空珊瑚涟漪,把"碰哪传哪"讲得能看懂、能上手。
HarmonyOS 7 把"空间坐标"交给了应用,我们能做的,是让每一次轻触都有回声。碰哪,传哪;落空,也有涟漪。
若你也在做鸿蒙 PC 的 Electron 应用,欢迎在评论区交流
hap:sign签名材料复用与libelectron.so的踩坑经验。
更多推荐



所有评论(0)