point.html 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>YOLO图片标注工具</title>
  6. <style>
  7. body { font-family: Arial, sans-serif; margin: 0; background: #f7f7f7; }
  8. #main-container {
  9. display: flex;
  10. height: 100vh;
  11. }
  12. #left-panel {
  13. width: 220px;
  14. background: #fff;
  15. border-right: 1px solid #eee;
  16. padding: 20px 10px 10px 10px;
  17. box-sizing: border-box;
  18. display: flex;
  19. flex-direction: column;
  20. }
  21. #imgList {
  22. flex: 1;
  23. overflow-y: auto;
  24. margin-top: 10px;
  25. }
  26. .img-url-item {
  27. padding: 6px 8px;
  28. border-radius: 4px;
  29. cursor: pointer;
  30. margin-bottom: 4px;
  31. transition: background 0.2s;
  32. }
  33. .img-url-item.active, .img-url-item:hover {
  34. background: #e6f7ff;
  35. }
  36. #center-panel {
  37. flex: 1;
  38. display: block;
  39. min-height: 600px;
  40. height: 100%;
  41. background: #f5f5f5;
  42. box-sizing: border-box;
  43. }
  44. .canvas-wrapper {
  45. width: 900px;
  46. height: 600px;
  47. background: #f5f5f5;
  48. position: relative;
  49. overflow: hidden;
  50. margin: 0 auto;
  51. display: block;
  52. }
  53. #canvas {
  54. border: 1px solid #ccc;
  55. cursor: crosshair;
  56. background: #acacac;
  57. box-shadow: 0 2px 8px #222;
  58. display: block;
  59. width: 900px;
  60. height: 600px;
  61. /* 宽高固定 */
  62. }
  63. #controls {
  64. margin-bottom: 10px;
  65. width: 100%;
  66. display: flex;
  67. gap: 8px;
  68. justify-content: center;
  69. }
  70. #right-panel {
  71. width: 260px;
  72. background: #fff;
  73. border-left: 1px solid #eee;
  74. padding: 20px 10px 10px 10px;
  75. box-sizing: border-box;
  76. display: flex;
  77. flex-direction: column;
  78. }
  79. #boxes-list {
  80. margin-top: 10px;
  81. flex: 1;
  82. overflow-y: auto;
  83. }
  84. .box-item {
  85. font-size: 14px;
  86. background: #f5f5f5;
  87. margin-bottom: 6px;
  88. padding: 6px 8px;
  89. border-radius: 4px;
  90. display: flex;
  91. justify-content: space-between;
  92. align-items: center;
  93. }
  94. .box-item.active {
  95. background: #ffe58f;
  96. border: 1.5px solid #faad14;
  97. }
  98. .del-btn {
  99. background: #ff7875;
  100. color: #fff;
  101. border: none;
  102. border-radius: 3px;
  103. padding: 2px 8px;
  104. cursor: pointer;
  105. font-size: 12px;
  106. }
  107. .del-btn:hover {
  108. background: #d9363e;
  109. }
  110. #exportBtn {
  111. margin-top: 10px;
  112. width: 100%;
  113. background: #1890ff;
  114. color: #fff;
  115. border: none;
  116. border-radius: 4px;
  117. padding: 8px 0;
  118. font-size: 15px;
  119. cursor: pointer;
  120. }
  121. #exportBtn:disabled {
  122. background: #ccc;
  123. color: #fff;
  124. cursor: not-allowed;
  125. }
  126. h2 { margin: 0 0 18px 0; text-align: center; }
  127. #imgUrlInput { width: 100%; box-sizing: border-box; }
  128. #loadImgBtn { width: 100%; }
  129. .img-thumb {
  130. width: 100%;
  131. max-width: 180px;
  132. height: 90px;
  133. object-fit: cover;
  134. border-radius: 6px;
  135. border: 2px solid transparent;
  136. margin-bottom: 8px;
  137. cursor: pointer;
  138. transition: border 0.2s;
  139. background: #f0f0f0;
  140. }
  141. .img-thumb.active {
  142. border: 2px solid #1890ff;
  143. }
  144. </style>
  145. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  146. </head>
  147. <body>
  148. <div id="main-container">
  149. <!-- 左侧图片列表 -->
  150. <div id="left-panel">
  151. <h2>图片列表</h2>
  152. <div id="imgList"></div>
  153. </div>
  154. <!-- 中间标注区 -->
  155. <div id="center-panel">
  156. <h2>图片标注区</h2>
  157. <div id="zoom-controls" style="margin:18px 0 10px 0;display:flex;gap:8px;justify-content:center;">
  158. <button id="prevImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">上一张</button>
  159. <button id="zoomInBtn" style="padding:4px 14px;">放大</button>
  160. <button id="zoomOutBtn" style="padding:4px 14px;">缩小</button>
  161. <button id="zoomResetBtn" style="padding:4px 14px;">重置</button>
  162. <button id="nextImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">下一张</button>
  163. </div>
  164. <div class="canvas-wrapper">
  165. <canvas id="canvas"></canvas>
  166. <div id="coordTip" style="position:fixed;display:none;pointer-events:none;z-index:9999;font-size:12px;color:#fff;background:rgba(0,0,0,0.7);padding:1px 6px;border-radius:4px;"></div>
  167. </div>
  168. </div>
  169. <!-- 右侧标注结果 -->
  170. <div id="right-panel">
  171. <h2>标注结果</h2>
  172. <div style="margin-bottom:10px;">
  173. <label for="classSelect">分类:</label>
  174. <select id="classSelect" style="font-size:15px;padding:2px 8px;">
  175. <option value="0">人</option>
  176. <option value="1">车</option>
  177. <option value="2">动物</option>
  178. </select>
  179. </div>
  180. <div id="boxes-list"></div>
  181. <button id="clearBoxesBtn" style="width:100%;margin-bottom:10px;background:#ff7875;color:#fff;border:none;border-radius:4px;padding:8px 0;font-size:15px;cursor:pointer;">清空所有标记</button>
  182. <button id="exportBtn" disabled style="margin-top:0;">导出YOLO标注</button>
  183. </div>
  184. </div>
  185. <script>
  186. // -------------------- 全局变量定义 --------------------
  187. let img = new window.Image(); // 当前加载的图片对象
  188. let boxes = []; // 当前图片的所有标注框数组
  189. let drawing = false; // 是否正在绘制新框
  190. let startX = 0, startY = 0, endX = 0, endY = 0; // 新建框的起止点(图片坐标)
  191. let imgWidth = 0, imgHeight = 0; // 当前图片的原始宽高
  192. let selectedBoxIndex = -1; // 当前选中的框索引
  193. let dragMode = null; // 拖动模式:null/move/resize
  194. let dragOffsetX = 0, dragOffsetY = 0; // 拖动时鼠标与框左上角的偏移
  195. const HANDLE_SIZE = 10; // 手柄的像素大小
  196. // 8个手柄类型,分别对应四个角和四条边中点
  197. const HANDLE_TYPES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
  198. // 缩放相关
  199. let imgScale = 1.0; // 图片缩放比例
  200. let minImgScale = 0.2, maxImgScale = 5.0; // 缩放上下限
  201. let imgOffsetX = 0, imgOffsetY = 0; // 图片在canvas内的平移
  202. let baseScale = 1.0; // 图片全图自适应时的缩放比例
  203. let spacePressed = false; // 是否按下空格
  204. let isPanning = false; // 是否正在拖动画布
  205. let panStart = {x: 0, y: 0}; // 拖动画布起点
  206. let panOffsetStart = {x: 0, y: 0}; // 拖动画布时的初始偏移
  207. // 分类配置:名称和颜色
  208. const classConfig = [
  209. { index: 0, name: '人', border: '#1890ff' },
  210. { index: 1, name: '车', border: '#52c41a' },
  211. { index: 2, name: '动物', border: '#722ed1' }
  212. ];
  213. // 辅助函数:将hex色转为rgba字符串,a为透明度
  214. function hexToRgba(hex, a) {
  215. hex = hex.replace('#', '');
  216. if (hex.length === 3) {
  217. hex = hex.split('').map(x => x + x).join('');
  218. }
  219. const r = parseInt(hex.substring(0,2), 16);
  220. const g = parseInt(hex.substring(2,4), 16);
  221. const b = parseInt(hex.substring(4,6), 16);
  222. return `rgba(${r},${g},${b},${a})`;
  223. }
  224. // -------------------- 工具函数 --------------------
  225. // 判断点(x, y)是否在框box内部(图片坐标)
  226. function isInBox(x, y, box) {
  227. return x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h;
  228. }
  229. // 获取8个手柄的中心坐标(用于缩放)
  230. function getHandles(box, size) {
  231. const x = box.x, y = box.y, w = box.w, h = box.h;
  232. const hs = (size || HANDLE_SIZE) / 2;
  233. return {
  234. nw: { x: x - hs, y: y - hs }, // 左上角
  235. n: { x: x + w/2 - hs, y: y - hs }, // 上中
  236. ne: { x: x + w - hs, y: y - hs }, // 右上角
  237. e: { x: x + w - hs, y: y + h/2 - hs }, // 右中
  238. se: { x: x + w - hs, y: y + h - hs }, // 右下角
  239. s: { x: x + w/2 - hs, y: y + h - hs }, // 下中
  240. sw: { x: x - hs, y: y + h - hs }, // 左下角
  241. w: { x: x - hs, y: y + h/2 - hs } // 左中
  242. };
  243. }
  244. // 判断点(x, y)是否在某个手柄上,返回手柄类型(canvas坐标)
  245. function getHandleAt(x, y, box) {
  246. let domW = $('#canvas').width();
  247. let pixelRatio = $('#canvas')[0].width / domW;
  248. let handleSize = 10 * pixelRatio;
  249. const handles = getHandles(box, handleSize);
  250. for (let type of HANDLE_TYPES) {
  251. const hx = handles[type].x, hy = handles[type].y;
  252. if (x >= hx && x <= hx + handleSize && y >= hy && y <= hy + handleSize) {
  253. return type;
  254. }
  255. }
  256. return null;
  257. }
  258. // 根据手柄类型设置鼠标指针样式
  259. function setCursorByHandle(type) {
  260. const map = {
  261. nw: 'nwse-resize',
  262. se: 'nwse-resize',
  263. ne: 'nesw-resize',
  264. sw: 'nesw-resize',
  265. n: 'ns-resize',
  266. s: 'ns-resize',
  267. e: 'ew-resize',
  268. w: 'ew-resize'
  269. };
  270. $('#canvas').css('cursor', map[type] || 'default');
  271. }
  272. // -------------------- 绘制函数 --------------------
  273. // 负责绘制图片、所有标注框、选中框的手柄、正在绘制的新框
  274. function drawAll() {
  275. const ctx = $('#canvas')[0].getContext('2d');
  276. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  277. ctx.save();
  278. const info = window._imgDrawInfo;
  279. if (info) {
  280. // 计算图片在canvas上的显示区域
  281. let drawW = info.imgWidth * imgScale;
  282. let drawH = info.imgHeight * imgScale;
  283. let drawX = (900 - drawW) / 2 + imgOffsetX;
  284. let drawY = (600 - drawH) / 2 + imgOffsetY;
  285. ctx.drawImage(img, drawX, drawY, drawW, drawH);
  286. }
  287. let lineWidth = 2;
  288. let handleSize = 10;
  289. // 绘制所有标注框
  290. boxes.forEach((box, idx) => {
  291. ctx.save();
  292. let c = toCanvasCoord(box.x, box.y); // 左上角canvas坐标
  293. let cw = box.w * imgScale;
  294. let ch = box.h * imgScale;
  295. // 先绘制半透明背景色和边框色,按分类区分
  296. if (idx === selectedBoxIndex) {
  297. ctx.fillStyle = 'rgba(255,200,0,0.18)'; // 选中填充
  298. ctx.strokeStyle = 'orange'; // 选中边框
  299. } else {
  300. const conf = classConfig.find(c => c.index === box.classId) || { border: 'red' };
  301. ctx.fillStyle = hexToRgba(conf.border, 0.18);
  302. ctx.strokeStyle = conf.border;
  303. }
  304. ctx.lineWidth = lineWidth;
  305. ctx.fillRect(c.x, c.y, cw, ch);
  306. ctx.strokeRect(c.x, c.y, cw, ch);
  307. // 绘制选中框的8个手柄
  308. if (idx === selectedBoxIndex) {
  309. ctx.fillStyle = 'blue';
  310. const handles = getHandles({x: c.x, y: c.y, w: cw, h: ch}, handleSize);
  311. for (let type of HANDLE_TYPES) {
  312. ctx.fillRect(handles[type].x, handles[type].y, handleSize, handleSize);
  313. }
  314. }
  315. ctx.restore();
  316. });
  317. // 绘制正在新建的框
  318. if (drawing) {
  319. ctx.strokeStyle = 'blue';
  320. ctx.lineWidth = lineWidth;
  321. let c1 = toCanvasCoord(startX, startY);
  322. let c2 = toCanvasCoord(endX, endY);
  323. ctx.strokeRect(
  324. Math.min(c1.x, c2.x),
  325. Math.min(c1.y, c2.y),
  326. Math.abs(c2.x - c1.x),
  327. Math.abs(c2.y - c1.y)
  328. );
  329. }
  330. ctx.restore();
  331. }
  332. // -------------------- 右侧标注框列表渲染 --------------------
  333. // 渲染右侧标注框列表,并高亮选中项
  334. function updateBoxesList() {
  335. let html = '';
  336. boxes.forEach((box, idx) => {
  337. const active = (idx === selectedBoxIndex) ? ' active' : '';
  338. html += `<div class="box-item${active}">
  339. 框${idx+1} [
  340. <select class='class-select' data-idx='${idx}' style='font-size:13px;padding:1px 6px;'>
  341. ${classConfig.map(c => `<option value="${c.index}"${box.classId==c.index?' selected':''}>${c.name}</option>`).join('')}
  342. </select>
  343. ] x:${box.x}, y:${box.y}, w:${box.w}, h:${box.h}
  344. <button data-idx="${idx}" class="del-btn">删除</button>
  345. </div>`;
  346. });
  347. $('#boxes-list').html(html);
  348. $('#exportBtn').prop('disabled', boxes.length === 0);
  349. }
  350. // -------------------- 坐标换算函数 --------------------
  351. // canvas坐标转图片坐标
  352. function toImageCoord(canvasX, canvasY) {
  353. const info = window._imgDrawInfo;
  354. if (!info) return {x: 0, y: 0};
  355. let drawW = info.imgWidth * imgScale;
  356. let drawH = info.imgHeight * imgScale;
  357. let drawX = (900 - drawW) / 2 + imgOffsetX;
  358. let drawY = (600 - drawH) / 2 + imgOffsetY;
  359. let x = (canvasX - drawX) / imgScale;
  360. let y = (canvasY - drawY) / imgScale;
  361. return {x, y};
  362. }
  363. // 图片坐标转canvas坐标
  364. function toCanvasCoord(imgX, imgY) {
  365. const info = window._imgDrawInfo;
  366. if (!info) return {x: 0, y: 0};
  367. let drawW = info.imgWidth * imgScale;
  368. let drawH = info.imgHeight * imgScale;
  369. let drawX = (900 - drawW) / 2 + imgOffsetX;
  370. let drawY = (600 - drawH) / 2 + imgOffsetY;
  371. let x = imgX * imgScale + drawX;
  372. let y = imgY * imgScale + drawY;
  373. return {x, y};
  374. }
  375. $(function() {
  376. // -------------------- 图片列表与mock数据 --------------------
  377. let imgUrlArr = [
  378. {
  379. id: 'img1',
  380. url: 'https://image.cszcyl.cn/2022/image/YfJA8eON3exqppNSQrW5EhE9rGdNS1qwou5dgj3L3651WcDDZEy89Hn1A296TXIx.png',
  381. boxes: [
  382. { x: 100, y: 120, w: 80, h: 60, classId: 0 },
  383. { x: 300, y: 200, w: 120, h: 90, classId: 0 }
  384. ]
  385. },
  386. {
  387. id: 'img2',
  388. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  389. boxes: [
  390. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  391. ]
  392. },
  393. {
  394. id: 'img2',
  395. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  396. boxes: [
  397. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  398. ]
  399. },
  400. {
  401. id: 'img2',
  402. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  403. boxes: [
  404. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  405. ]
  406. },
  407. {
  408. id: 'img2',
  409. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  410. boxes: [
  411. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  412. ]
  413. },
  414. {
  415. id: 'img2',
  416. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  417. boxes: [
  418. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  419. ]
  420. },
  421. {
  422. id: 'img2',
  423. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  424. boxes: [
  425. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  426. ]
  427. },
  428. {
  429. id: 'img2',
  430. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  431. boxes: [
  432. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  433. ]
  434. },
  435. {
  436. id: 'img2',
  437. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  438. boxes: [
  439. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  440. ]
  441. },
  442. {
  443. id: 'img2',
  444. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  445. boxes: [
  446. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  447. ]
  448. },
  449. {
  450. id: 'img2',
  451. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  452. boxes: [
  453. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  454. ]
  455. },
  456. {
  457. id: 'img2',
  458. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  459. boxes: [
  460. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  461. ]
  462. },
  463. {
  464. id: 'img2',
  465. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  466. boxes: [
  467. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  468. ]
  469. },
  470. {
  471. id: 'img2',
  472. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  473. boxes: [
  474. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  475. ]
  476. },
  477. {
  478. id: 'img2',
  479. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  480. boxes: [
  481. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  482. ]
  483. }
  484. ];
  485. let currentImgIndex = 0; // 当前图片索引
  486. // 渲染左侧图片缩略图列表
  487. function renderImgList() {
  488. let html = '';
  489. imgUrlArr.forEach((item, idx) => {
  490. html += `<img src="${item.url}" class="img-thumb${idx===currentImgIndex?' active':''}" data-idx="${idx}" title="${item.url}">`;
  491. });
  492. $('#imgList').html(html);
  493. // 渲染后自动滚动选中图片到可见区域并居中
  494. setTimeout(() => {
  495. const $active = $('#imgList .img-thumb.active')[0];
  496. if ($active) $active.scrollIntoView({ block: 'center', behavior: 'auto' });
  497. }, 0);
  498. }
  499. renderImgList();
  500. // 点击图片缩略图切换图片
  501. $('#imgList').on('click', '.img-thumb', function() {
  502. const idx = $(this).data('idx');
  503. if (currentImgIndex === idx) return;
  504. currentImgIndex = idx;
  505. renderImgList();
  506. loadCurrentImage();
  507. });
  508. // 加载当前选中图片到canvas,并初始化标注框
  509. function loadCurrentImage() {
  510. const imgObj = imgUrlArr[currentImgIndex];
  511. const url = imgObj.url;
  512. // 更新按钮禁用状态
  513. $('#prevImgBtn').prop('disabled', currentImgIndex === 0);
  514. $('#nextImgBtn').prop('disabled', currentImgIndex === imgUrlArr.length - 1);
  515. // 先解绑,防止多次触发
  516. img.onload = null;
  517. img.onerror = null;
  518. img.onload = function() {
  519. imgWidth = img.width;
  520. imgHeight = img.height;
  521. // 计算自适应缩放比例
  522. if (imgWidth <= 900 && imgHeight <= 600) {
  523. baseScale = 1;
  524. } else {
  525. baseScale = Math.min(900 / imgWidth, 600 / imgHeight);
  526. }
  527. imgScale = baseScale;
  528. imgOffsetX = 0;
  529. imgOffsetY = 0;
  530. window._imgDrawInfo = {imgWidth, imgHeight};
  531. $('#canvas').attr({ width: 900, height: 600 });
  532. $('#canvas').css({ width: '900px', height: '600px', margin: 0, padding: 0 });
  533. // 初始化标注框
  534. boxes = imgObj.boxes ? JSON.parse(JSON.stringify(imgObj.boxes)) : [];
  535. selectedBoxIndex = -1;
  536. drawAll();
  537. updateBoxesList();
  538. };
  539. img.onerror = function() {
  540. alert('图片加载失败,请检查URL是否正确');
  541. };
  542. img.src = url;
  543. }
  544. // 页面加载时自动加载第一张图片
  545. loadCurrentImage();
  546. let resizeHandle = null; // 当前正在拖动的手柄类型
  547. // 监听键盘空格按下/松开(用于画布拖动)
  548. $(document).on('keydown', function(e) {
  549. if (e.code === 'Space') spacePressed = true;
  550. });
  551. $(document).on('keyup', function(e) {
  552. if (e.code === 'Space') spacePressed = false;
  553. });
  554. // -------------------- canvas鼠标事件 --------------------
  555. // 鼠标按下事件
  556. $('#canvas').on('mousedown', function(e) {
  557. if (!imgWidth) return;
  558. const rect = this.getBoundingClientRect();
  559. const canvasX = e.clientX - rect.left;
  560. const canvasY = e.clientY - rect.top;
  561. // 新增:空格+左键 或 右键拖动画布
  562. if ((spacePressed && e.button === 0) || e.button === 2) {
  563. isPanning = true;
  564. panStart = {x: e.clientX, y: e.clientY};
  565. panOffsetStart = {x: imgOffsetX, y: imgOffsetY};
  566. $('#canvas').css('cursor', 'grab');
  567. return;
  568. }
  569. let found = false;
  570. resizeHandle = null;
  571. // 优先判断是否点中手柄或框(全部用canvas坐标判定)
  572. for (let i = boxes.length - 1; i >= 0; i--) {
  573. let cbox = toCanvasCoord(boxes[i].x, boxes[i].y);
  574. let cw = boxes[i].w * imgScale;
  575. let ch = boxes[i].h * imgScale;
  576. const handleType = getHandleAt(canvasX, canvasY, {x: cbox.x, y: cbox.y, w: cw, h: ch});
  577. if (handleType) {
  578. selectedBoxIndex = i;
  579. dragMode = 'resize';
  580. resizeHandle = handleType;
  581. found = true;
  582. break;
  583. } else if (
  584. canvasX >= cbox.x && canvasX <= cbox.x + cw &&
  585. canvasY >= cbox.y && canvasY <= cbox.y + ch
  586. ) {
  587. selectedBoxIndex = i;
  588. dragMode = 'move';
  589. dragOffsetX = toImageCoord(canvasX, canvasY).x - boxes[i].x;
  590. dragOffsetY = toImageCoord(canvasX, canvasY).y - boxes[i].y;
  591. found = true;
  592. break;
  593. }
  594. }
  595. if (found) {
  596. drawing = false;
  597. } else {
  598. // 没点中任何框,开始新建或取消选中
  599. selectedBoxIndex = -1;
  600. // 新建时,只有初始点在图片区域内才允许框选
  601. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  602. if (mouseX >= 0 && mouseX <= imgWidth && mouseY >= 0 && mouseY <= imgHeight) {
  603. drawing = true;
  604. startX = mouseX;
  605. startY = mouseY;
  606. endX = mouseX;
  607. endY = mouseY;
  608. }
  609. }
  610. // 无论如何都刷新一次,保证视觉同步
  611. drawAll();
  612. updateBoxesList();
  613. });
  614. // 鼠标移动事件
  615. $('#canvas').on('mousemove', function(e) {
  616. const rect = this.getBoundingClientRect();
  617. const canvasX = e.clientX - rect.left;
  618. const canvasY = e.clientY - rect.top;
  619. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  620. // 实时显示坐标
  621. if (imgWidth) {
  622. let showX = Math.round(mouseX);
  623. let showY = Math.round(mouseY);
  624. if (showX >= 0 && showX <= imgWidth && showY >= 0 && showY <= imgHeight) {
  625. $('#coordTip').text(`${showX}, ${showY}`).css({
  626. left: (e.clientX - 10) + 'px',
  627. top: (e.clientY - 28) + 'px',
  628. display: 'block'
  629. });
  630. } else {
  631. $('#coordTip').hide();
  632. }
  633. }
  634. // 新增:画布拖拽
  635. if (isPanning) {
  636. let dx = e.clientX - panStart.x;
  637. let dy = e.clientY - panStart.y;
  638. imgOffsetX = panOffsetStart.x + dx;
  639. imgOffsetY = panOffsetStart.y + dy;
  640. drawAll();
  641. return;
  642. }
  643. if (drawing) {
  644. // 新建框时,动态绘制,限制不出界
  645. endX = Math.max(0, Math.min(mouseX, imgWidth));
  646. endY = Math.max(0, Math.min(mouseY, imgHeight));
  647. drawAll();
  648. } else if (selectedBoxIndex !== -1 && dragMode) {
  649. let box = boxes[selectedBoxIndex];
  650. let minW = 10, minH = 10;
  651. let x = box.x, y = box.y, w = box.w, h = box.h;
  652. if (dragMode === 'move') {
  653. // 拖动移动框
  654. let newX = mouseX - dragOffsetX;
  655. let newY = mouseY - dragOffsetY;
  656. newX = Math.max(0, Math.min(newX, imgWidth - w));
  657. newY = Math.max(0, Math.min(newY, imgHeight - h));
  658. box.x = newX;
  659. box.y = newY;
  660. } else if (dragMode === 'resize' && resizeHandle) {
  661. // 8方向缩放
  662. switch (resizeHandle) {
  663. case 'nw': // 左上角
  664. box.x = Math.min(mouseX, x + w - minW);
  665. box.y = Math.min(mouseY, y + h - minH);
  666. box.w = w + (x - box.x);
  667. box.h = h + (y - box.y);
  668. break;
  669. case 'n': // 上中
  670. box.y = Math.min(mouseY, y + h - minH);
  671. box.h = h + (y - box.y);
  672. break;
  673. case 'ne': // 右上角
  674. box.y = Math.min(mouseY, y + h - minH);
  675. box.w = Math.max(minW, mouseX - x);
  676. box.h = h + (y - box.y);
  677. break;
  678. case 'e': // 右中
  679. box.w = Math.max(minW, mouseX - x);
  680. break;
  681. case 'se': // 右下角
  682. box.w = Math.max(minW, mouseX - x);
  683. box.h = Math.max(minH, mouseY - y);
  684. break;
  685. case 's': // 下中
  686. box.h = Math.max(minH, mouseY - y);
  687. break;
  688. case 'sw': // 左下角
  689. box.x = Math.min(mouseX, x + w - minW);
  690. box.w = w + (x - box.x);
  691. box.h = Math.max(minH, mouseY - y);
  692. break;
  693. case 'w': // 左中
  694. box.x = Math.min(mouseX, x + w - minW);
  695. box.w = w + (x - box.x);
  696. break;
  697. }
  698. // 限制不出界
  699. if (box.x < 0) { box.w += box.x; box.x = 0; }
  700. if (box.y < 0) { box.h += box.y; box.y = 0; }
  701. if (box.x + box.w > imgWidth) box.w = imgWidth - box.x;
  702. if (box.y + box.h > imgHeight) box.h = imgHeight - box.y;
  703. }
  704. drawAll();
  705. updateBoxesList();
  706. } else if (selectedBoxIndex !== -1) {
  707. // 悬停手柄时改变鼠标样式
  708. const box = boxes[selectedBoxIndex];
  709. const handleType = getHandleAt(mouseX, mouseY, box);
  710. setCursorByHandle(handleType);
  711. } else {
  712. $('#canvas').css('cursor', 'crosshair');
  713. }
  714. });
  715. // 鼠标松开事件
  716. $(document).on('mouseup', function(e) {
  717. if (isPanning) {
  718. isPanning = false;
  719. $('#canvas').css('cursor', spacePressed ? 'grab' : 'crosshair');
  720. return;
  721. }
  722. const rect = $('#canvas')[0].getBoundingClientRect();
  723. const canvasX = e.clientX - rect.left;
  724. const canvasY = e.clientY - rect.top;
  725. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  726. if (drawing) {
  727. drawing = false;
  728. // 重新用toImageCoord获取endX、endY,保证为图片原始坐标
  729. endX = Math.max(0, Math.min(mouseX, imgWidth));
  730. endY = Math.max(0, Math.min(mouseY, imgHeight));
  731. const x = Math.max(0, Math.min(startX, endX));
  732. const y = Math.max(0, Math.min(startY, endY));
  733. let w = Math.abs(endX - startX);
  734. let h = Math.abs(endY - startY);
  735. // 再次限制宽高不超界
  736. if (x + w > imgWidth) w = imgWidth - x;
  737. if (y + h > imgHeight) h = imgHeight - y;
  738. if (w > 5 && h > 5) {
  739. // 新建框时用当前分类
  740. const classId = parseInt($('#classSelect').val(), 10);
  741. boxes.push({ x, y, w, h, classId });
  742. // 同步到图片对象的boxes
  743. imgUrlArr[currentImgIndex].boxes = JSON.parse(JSON.stringify(boxes));
  744. // 新增后默认选中该框
  745. selectedBoxIndex = boxes.length - 1;
  746. }
  747. drawAll();
  748. updateBoxesList();
  749. }
  750. // 鼠标松开后,始终清空拖动/缩放状态
  751. dragMode = null;
  752. resizeHandle = null;
  753. });
  754. // 删除按钮事件
  755. $('#boxes-list').on('click', '.del-btn', function() {
  756. const idx = $(this).data('idx');
  757. boxes.splice(idx, 1);
  758. if (selectedBoxIndex === idx) selectedBoxIndex = -1;
  759. drawAll();
  760. updateBoxesList();
  761. // 同步到图片对象的boxes
  762. imgUrlArr[currentImgIndex].boxes = JSON.parse(JSON.stringify(boxes));
  763. });
  764. // 支持选中边框时按Delete键删除
  765. $(document).on('keydown', function(e) {
  766. if ((e.key === 'Delete' || e.key === 'Backspace') && selectedBoxIndex !== -1 && boxes.length > 0) {
  767. boxes.splice(selectedBoxIndex, 1);
  768. selectedBoxIndex = -1;
  769. drawAll();
  770. updateBoxesList();
  771. imgUrlArr[currentImgIndex].boxes = JSON.parse(JSON.stringify(boxes));
  772. }
  773. });
  774. // 右侧标注项点击选中,联动canvas高亮
  775. $('#boxes-list').on('click', '.box-item', function(e) {
  776. // 避免点击删除按钮或下拉框时触发
  777. if (
  778. $(e.target).hasClass('del-btn') ||
  779. $(e.target).hasClass('class-select') ||
  780. e.target.tagName === 'SELECT' ||
  781. e.target.tagName === 'OPTION'
  782. ) return;
  783. const idx = $(this).index();
  784. selectedBoxIndex = idx;
  785. drawAll();
  786. updateBoxesList();
  787. });
  788. // 右侧分类下拉框修改事件
  789. $('#boxes-list').on('change', '.class-select', function() {
  790. const idx = $(this).data('idx');
  791. const val = parseInt($(this).val(), 10);
  792. if (boxes[idx]) {
  793. boxes[idx].classId = val;
  794. updateBoxesList();
  795. drawAll();
  796. // 同步到图片对象的boxes
  797. imgUrlArr[currentImgIndex].boxes = JSON.parse(JSON.stringify(boxes));
  798. }
  799. });
  800. // -------------------- 导出/清空/缩放/切换图片等事件 --------------------
  801. // 导出YOLO格式标注
  802. $('#exportBtn').on('click', function() {
  803. // YOLO格式: class x_center y_center width height (均为归一化)
  804. let lines = boxes.map(box => {
  805. const x_center = (box.x + box.w / 2) / imgWidth;
  806. const y_center = (box.y + box.h / 2) / imgHeight;
  807. const w = box.w / imgWidth;
  808. const h = box.h / imgHeight;
  809. return `${box.classId} ${x_center} ${y_center} ${w} ${h}`;
  810. });
  811. const blob = new Blob([lines.join('\n')], { type: 'text/plain' });
  812. const a = document.createElement('a');
  813. a.href = URL.createObjectURL(blob);
  814. a.download = 'labels.txt';
  815. a.click();
  816. });
  817. // 清空所有标记按钮
  818. $('#clearBoxesBtn').on('click', function() {
  819. boxes = [];
  820. drawAll();
  821. updateBoxesList();
  822. // 同步到图片对象的boxes
  823. imgUrlArr[currentImgIndex].boxes = [];
  824. });
  825. // 放大缩小按钮事件
  826. $('#zoomInBtn').on('click', function() {
  827. imgScale = Math.min(maxImgScale, imgScale * 1.2);
  828. drawAll();
  829. });
  830. $('#zoomOutBtn').on('click', function() {
  831. imgScale = Math.max(minImgScale, imgScale / 1.2);
  832. drawAll();
  833. });
  834. $('#zoomResetBtn').on('click', function() {
  835. imgScale = baseScale;
  836. imgOffsetX = 0;
  837. imgOffsetY = 0;
  838. drawAll();
  839. });
  840. // 鼠标滚轮缩放(以鼠标为中心)
  841. $('#canvas').on('wheel', function(e) {
  842. e.preventDefault();
  843. let mouseX = e.offsetX, mouseY = e.offsetY;
  844. // 1. 记录缩放前鼠标在图片上的坐标
  845. let before = toImageCoord(mouseX, mouseY);
  846. // 2. 计算缩放
  847. if (e.originalEvent.deltaY < 0) {
  848. imgScale = Math.min(maxImgScale, imgScale * 1.1);
  849. } else {
  850. imgScale = Math.max(minImgScale, imgScale / 1.1);
  851. }
  852. // 3. 计算缩放后该点在canvas上的新位置
  853. let after = toCanvasCoord(before.x, before.y);
  854. // 4. 调整offset,使鼠标下的图片点不动
  855. imgOffsetX += (mouseX - after.x);
  856. imgOffsetY += (mouseY - after.y);
  857. drawAll();
  858. });
  859. // 禁止右键菜单弹出
  860. $('#canvas').on('contextmenu', function(e) { e.preventDefault(); });
  861. // 鼠标移出canvas时隐藏坐标提示
  862. $('#canvas').on('mouseleave', function() {
  863. $('#coordTip').hide();
  864. });
  865. // 按钮切换上一张/下一张图片
  866. $('#prevImgBtn').on('click', function() {
  867. if (currentImgIndex > 0) {
  868. currentImgIndex--;
  869. renderImgList();
  870. loadCurrentImage();
  871. }
  872. });
  873. $('#nextImgBtn').on('click', function() {
  874. if (currentImgIndex < imgUrlArr.length - 1) {
  875. currentImgIndex++;
  876. renderImgList();
  877. loadCurrentImage();
  878. }
  879. });
  880. });
  881. </script>
  882. </body>
  883. </html>