point.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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. #filename {
  145. color: #ccc;
  146. font-size: 15px;
  147. margin-top: 10px;
  148. text-align: center;
  149. }
  150. </style>
  151. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  152. </head>
  153. <body>
  154. <div id="main-container">
  155. <!-- 左侧图片列表 -->
  156. <div id="left-panel">
  157. <h2>图片列表</h2>
  158. <div id="imgList"></div>
  159. </div>
  160. <!-- 中间标注区 -->
  161. <div id="center-panel">
  162. <h2>图片标注区</h2>
  163. <div id="zoom-controls" style="margin:18px 0 10px 0;display:flex;gap:8px;justify-content:center;">
  164. <button id="prevImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">上一张</button>
  165. <button id="zoomInBtn" style="padding:4px 14px;">放大</button>
  166. <button id="zoomOutBtn" style="padding:4px 14px;">缩小</button>
  167. <button id="zoomResetBtn" style="padding:4px 14px;">重置</button>
  168. <button id="nextImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">下一张</button>
  169. </div>
  170. <div class="canvas-wrapper">
  171. <canvas id="canvas"></canvas>
  172. <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>
  173. </div>
  174. <div id="filename" style="color:#ccc;font-size:15px;margin:16px 0 0 0;text-align:center;"></div>
  175. </div>
  176. <!-- 右侧标注结果 -->
  177. <div id="right-panel">
  178. <h2>标注结果</h2>
  179. <div id="boxes-list"></div>
  180. <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>
  181. <button id="exportBtn" disabled style="margin-top:0;">导出YOLO标注</button>
  182. </div>
  183. </div>
  184. <script>
  185. // -------------------- 全局变量定义 --------------------
  186. let img = new window.Image(); // 当前加载的图片对象
  187. let boxes = []; // 当前图片的所有标注框数组
  188. let drawing = false; // 是否正在绘制新框
  189. let startX = 0, startY = 0, endX = 0, endY = 0; // 新建框的起止点(图片坐标)
  190. let imgWidth = 0, imgHeight = 0; // 当前图片的原始宽高
  191. let selectedBoxIndex = -1; // 当前选中的框索引
  192. let dragMode = null; // 拖动模式:null/move/resize
  193. let dragOffsetX = 0, dragOffsetY = 0; // 拖动时鼠标与框左上角的偏移
  194. const HANDLE_SIZE = 10; // 手柄的像素大小
  195. // 8个手柄类型,分别对应四个角和四条边中点
  196. const HANDLE_TYPES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
  197. // 缩放相关
  198. let imgScale = 1.0; // 图片缩放比例
  199. let minImgScale = 0.2, maxImgScale = 5.0; // 缩放上下限
  200. let imgOffsetX = 0, imgOffsetY = 0; // 图片在canvas内的平移
  201. let baseScale = 1.0; // 图片全图自适应时的缩放比例
  202. let spacePressed = false; // 是否按下空格
  203. let isPanning = false; // 是否正在拖动画布
  204. let panStart = {x: 0, y: 0}; // 拖动画布起点
  205. let panOffsetStart = {x: 0, y: 0}; // 拖动画布时的初始偏移
  206. // -------------------- 工具函数 --------------------
  207. // 判断点(x, y)是否在框box内部(图片坐标)
  208. function isInBox(x, y, box) {
  209. return x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h;
  210. }
  211. // 获取8个手柄的中心坐标(用于缩放)
  212. function getHandles(box, size) {
  213. const x = box.x, y = box.y, w = box.w, h = box.h;
  214. const hs = (size || HANDLE_SIZE) / 2;
  215. return {
  216. nw: { x: x - hs, y: y - hs }, // 左上角
  217. n: { x: x + w/2 - hs, y: y - hs }, // 上中
  218. ne: { x: x + w - hs, y: y - hs }, // 右上角
  219. e: { x: x + w - hs, y: y + h/2 - hs }, // 右中
  220. se: { x: x + w - hs, y: y + h - hs }, // 右下角
  221. s: { x: x + w/2 - hs, y: y + h - hs }, // 下中
  222. sw: { x: x - hs, y: y + h - hs }, // 左下角
  223. w: { x: x - hs, y: y + h/2 - hs } // 左中
  224. };
  225. }
  226. // 判断点(x, y)是否在某个手柄上,返回手柄类型(canvas坐标)
  227. function getHandleAt(x, y, box) {
  228. let domW = $('#canvas').width();
  229. let pixelRatio = $('#canvas')[0].width / domW;
  230. let handleSize = 10 * pixelRatio;
  231. const handles = getHandles(box, handleSize);
  232. for (let type of HANDLE_TYPES) {
  233. const hx = handles[type].x, hy = handles[type].y;
  234. if (x >= hx && x <= hx + handleSize && y >= hy && y <= hy + handleSize) {
  235. return type;
  236. }
  237. }
  238. return null;
  239. }
  240. // 根据手柄类型设置鼠标指针样式
  241. function setCursorByHandle(type) {
  242. const map = {
  243. nw: 'nwse-resize',
  244. se: 'nwse-resize',
  245. ne: 'nesw-resize',
  246. sw: 'nesw-resize',
  247. n: 'ns-resize',
  248. s: 'ns-resize',
  249. e: 'ew-resize',
  250. w: 'ew-resize'
  251. };
  252. $('#canvas').css('cursor', map[type] || 'default');
  253. }
  254. // -------------------- 绘制函数 --------------------
  255. // 负责绘制图片、所有标注框、选中框的手柄、正在绘制的新框
  256. function drawAll() {
  257. const ctx = $('#canvas')[0].getContext('2d');
  258. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  259. ctx.save();
  260. const info = window._imgDrawInfo;
  261. if (info) {
  262. // 计算图片在canvas上的显示区域
  263. let drawW = info.imgWidth * imgScale;
  264. let drawH = info.imgHeight * imgScale;
  265. let drawX = (900 - drawW) / 2 + imgOffsetX;
  266. let drawY = (600 - drawH) / 2 + imgOffsetY;
  267. ctx.drawImage(img, drawX, drawY, drawW, drawH);
  268. }
  269. let lineWidth = 2;
  270. let handleSize = 10;
  271. // 绘制所有标注框
  272. boxes.forEach((box, idx) => {
  273. ctx.save();
  274. let c = toCanvasCoord(box.x, box.y); // 左上角canvas坐标
  275. let cw = box.w * imgScale;
  276. let ch = box.h * imgScale;
  277. // 先绘制半透明背景色
  278. if (idx === selectedBoxIndex) {
  279. ctx.fillStyle = 'rgba(255,200,0,0.18)';
  280. } else {
  281. ctx.fillStyle = 'rgba(255,0,0,0.18)';
  282. }
  283. ctx.fillRect(c.x, c.y, cw, ch);
  284. if (idx === selectedBoxIndex) {
  285. ctx.strokeStyle = 'orange'; // 选中高亮
  286. ctx.lineWidth = lineWidth;
  287. } else {
  288. ctx.strokeStyle = 'red';
  289. ctx.lineWidth = lineWidth;
  290. }
  291. ctx.strokeRect(c.x, c.y, cw, ch);
  292. // 绘制选中框的8个手柄
  293. if (idx === selectedBoxIndex) {
  294. ctx.fillStyle = 'blue';
  295. const handles = getHandles({x: c.x, y: c.y, w: cw, h: ch}, handleSize);
  296. for (let type of HANDLE_TYPES) {
  297. ctx.fillRect(handles[type].x, handles[type].y, handleSize, handleSize);
  298. }
  299. }
  300. ctx.restore();
  301. });
  302. // 绘制正在新建的框
  303. if (drawing) {
  304. ctx.strokeStyle = 'blue';
  305. ctx.lineWidth = lineWidth;
  306. let c1 = toCanvasCoord(startX, startY);
  307. let c2 = toCanvasCoord(endX, endY);
  308. ctx.strokeRect(
  309. Math.min(c1.x, c2.x),
  310. Math.min(c1.y, c2.y),
  311. Math.abs(c2.x - c1.x),
  312. Math.abs(c2.y - c1.y)
  313. );
  314. }
  315. ctx.restore();
  316. }
  317. // -------------------- 右侧标注框列表渲染 --------------------
  318. // 渲染右侧标注框列表,并高亮选中项
  319. function updateBoxesList() {
  320. let html = '';
  321. boxes.forEach((box, idx) => {
  322. const active = (idx === selectedBoxIndex) ? ' active' : '';
  323. html += `<div class="box-item${active}">框${idx+1} [x:${box.x}, y:${box.y}, w:${box.w}, h:${box.h}] <button data-idx="${idx}" class="del-btn">删除</button></div>`;
  324. });
  325. $('#boxes-list').html(html);
  326. $('#exportBtn').prop('disabled', boxes.length === 0);
  327. }
  328. // -------------------- 坐标换算函数 --------------------
  329. // canvas坐标转图片坐标
  330. function toImageCoord(canvasX, canvasY) {
  331. const info = window._imgDrawInfo;
  332. if (!info) return {x: 0, y: 0};
  333. let drawW = info.imgWidth * imgScale;
  334. let drawH = info.imgHeight * imgScale;
  335. let drawX = (900 - drawW) / 2 + imgOffsetX;
  336. let drawY = (600 - drawH) / 2 + imgOffsetY;
  337. let x = (canvasX - drawX) / imgScale;
  338. let y = (canvasY - drawY) / imgScale;
  339. return {x, y};
  340. }
  341. // 图片坐标转canvas坐标
  342. function toCanvasCoord(imgX, imgY) {
  343. const info = window._imgDrawInfo;
  344. if (!info) return {x: 0, y: 0};
  345. let drawW = info.imgWidth * imgScale;
  346. let drawH = info.imgHeight * imgScale;
  347. let drawX = (900 - drawW) / 2 + imgOffsetX;
  348. let drawY = (600 - drawH) / 2 + imgOffsetY;
  349. let x = imgX * imgScale + drawX;
  350. let y = imgY * imgScale + drawY;
  351. return {x, y};
  352. }
  353. $(function() {
  354. // -------------------- 图片列表与mock数据 --------------------
  355. // 图片URL缩略图列表,默认两张图片
  356. let imgUrlArr = [
  357. 'https://image.cszcyl.cn/2022/image/YfJA8eON3exqppNSQrW5EhE9rGdNS1qwou5dgj3L3651WcDDZEy89Hn1A296TXIx.png',
  358. 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png'
  359. ];
  360. let currentImgIndex = 0; // 当前图片索引
  361. // mock 标注数据,key为图片url
  362. let mockBoxes = {
  363. 'https://image.cszcyl.cn/2022/image/YfJA8eON3exqppNSQrW5EhE9rGdNS1qwou5dgj3L3651WcDDZEy89Hn1A296TXIx.png': [
  364. { x: 100, y: 120, w: 80, h: 60, classId: 0 },
  365. { x: 300, y: 200, w: 120, h: 90, classId: 0 }
  366. ],
  367. 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png': [
  368. { x: 50, y: 50, w: 60, h: 60, classId: 0 }
  369. ]
  370. // 其它图片可继续添加
  371. };
  372. // 渲染左侧图片缩略图列表
  373. function renderImgList() {
  374. let html = '';
  375. imgUrlArr.forEach((url, idx) => {
  376. html += `<img src="${url}" class="img-thumb${idx===currentImgIndex?' active':''}" data-idx="${idx}" title="${url}">`;
  377. });
  378. $('#imgList').html(html);
  379. }
  380. renderImgList();
  381. // 点击图片缩略图切换图片
  382. $('#imgList').on('click', '.img-thumb', function() {
  383. const idx = $(this).data('idx');
  384. if (currentImgIndex === idx) return;
  385. currentImgIndex = idx;
  386. renderImgList();
  387. loadCurrentImage();
  388. });
  389. // 加载当前选中图片到canvas,并初始化标注框
  390. function loadCurrentImage() {
  391. const url = imgUrlArr[currentImgIndex];
  392. // 显示文件名
  393. const name = url.split('/').pop();
  394. $('#filename').text(name);
  395. // 更新按钮禁用状态
  396. $('#prevImgBtn').prop('disabled', currentImgIndex === 0);
  397. $('#nextImgBtn').prop('disabled', currentImgIndex === imgUrlArr.length - 1);
  398. // 先解绑,防止多次触发
  399. img.onload = null;
  400. img.onerror = null;
  401. img.onload = function() {
  402. imgWidth = img.width;
  403. imgHeight = img.height;
  404. // 计算自适应缩放比例
  405. if (imgWidth <= 900 && imgHeight <= 600) {
  406. baseScale = 1;
  407. } else {
  408. baseScale = Math.min(900 / imgWidth, 600 / imgHeight);
  409. }
  410. imgScale = baseScale;
  411. imgOffsetX = 0;
  412. imgOffsetY = 0;
  413. window._imgDrawInfo = {imgWidth, imgHeight};
  414. $('#canvas').attr({ width: 900, height: 600 });
  415. $('#canvas').css({ width: '900px', height: '600px', margin: 0, padding: 0 });
  416. // 初始化标注框
  417. boxes = mockBoxes[url] ? JSON.parse(JSON.stringify(mockBoxes[url])) : [];
  418. selectedBoxIndex = -1;
  419. drawAll();
  420. updateBoxesList();
  421. };
  422. img.onerror = function() {
  423. alert('图片加载失败,请检查URL是否正确');
  424. };
  425. img.src = url;
  426. }
  427. // 页面加载时自动加载第一张图片
  428. loadCurrentImage();
  429. let resizeHandle = null; // 当前正在拖动的手柄类型
  430. // 监听键盘空格按下/松开(用于画布拖动)
  431. $(document).on('keydown', function(e) {
  432. if (e.code === 'Space') spacePressed = true;
  433. });
  434. $(document).on('keyup', function(e) {
  435. if (e.code === 'Space') spacePressed = false;
  436. });
  437. // -------------------- canvas鼠标事件 --------------------
  438. // 鼠标按下事件
  439. $('#canvas').on('mousedown', function(e) {
  440. if (!imgWidth) return;
  441. const rect = this.getBoundingClientRect();
  442. const canvasX = e.clientX - rect.left;
  443. const canvasY = e.clientY - rect.top;
  444. // 新增:空格+左键 或 右键拖动画布
  445. if ((spacePressed && e.button === 0) || e.button === 2) {
  446. isPanning = true;
  447. panStart = {x: e.clientX, y: e.clientY};
  448. panOffsetStart = {x: imgOffsetX, y: imgOffsetY};
  449. $('#canvas').css('cursor', 'grab');
  450. return;
  451. }
  452. let found = false;
  453. resizeHandle = null;
  454. // 优先判断是否点中手柄或框(全部用canvas坐标判定)
  455. for (let i = boxes.length - 1; i >= 0; i--) {
  456. let cbox = toCanvasCoord(boxes[i].x, boxes[i].y);
  457. let cw = boxes[i].w * imgScale;
  458. let ch = boxes[i].h * imgScale;
  459. const handleType = getHandleAt(canvasX, canvasY, {x: cbox.x, y: cbox.y, w: cw, h: ch});
  460. if (handleType) {
  461. selectedBoxIndex = i;
  462. dragMode = 'resize';
  463. resizeHandle = handleType;
  464. found = true;
  465. break;
  466. } else if (
  467. canvasX >= cbox.x && canvasX <= cbox.x + cw &&
  468. canvasY >= cbox.y && canvasY <= cbox.y + ch
  469. ) {
  470. selectedBoxIndex = i;
  471. dragMode = 'move';
  472. dragOffsetX = toImageCoord(canvasX, canvasY).x - boxes[i].x;
  473. dragOffsetY = toImageCoord(canvasX, canvasY).y - boxes[i].y;
  474. found = true;
  475. break;
  476. }
  477. }
  478. if (found) {
  479. drawing = false;
  480. } else {
  481. // 没点中任何框,开始新建或取消选中
  482. selectedBoxIndex = -1;
  483. // 新建时,只有初始点在图片区域内才允许框选
  484. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  485. if (mouseX >= 0 && mouseX <= imgWidth && mouseY >= 0 && mouseY <= imgHeight) {
  486. drawing = true;
  487. startX = mouseX;
  488. startY = mouseY;
  489. endX = mouseX;
  490. endY = mouseY;
  491. }
  492. }
  493. // 无论如何都刷新一次,保证视觉同步
  494. drawAll();
  495. updateBoxesList();
  496. });
  497. // 鼠标移动事件
  498. $('#canvas').on('mousemove', function(e) {
  499. const rect = this.getBoundingClientRect();
  500. const canvasX = e.clientX - rect.left;
  501. const canvasY = e.clientY - rect.top;
  502. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  503. // 实时显示坐标
  504. if (imgWidth) {
  505. let showX = Math.round(mouseX);
  506. let showY = Math.round(mouseY);
  507. if (showX >= 0 && showX <= imgWidth && showY >= 0 && showY <= imgHeight) {
  508. $('#coordTip').text(`${showX}, ${showY}`).css({
  509. left: (e.clientX - 10) + 'px',
  510. top: (e.clientY - 28) + 'px',
  511. display: 'block'
  512. });
  513. } else {
  514. $('#coordTip').hide();
  515. }
  516. }
  517. // 新增:画布拖拽
  518. if (isPanning) {
  519. let dx = e.clientX - panStart.x;
  520. let dy = e.clientY - panStart.y;
  521. imgOffsetX = panOffsetStart.x + dx;
  522. imgOffsetY = panOffsetStart.y + dy;
  523. drawAll();
  524. return;
  525. }
  526. if (drawing) {
  527. // 新建框时,动态绘制,限制不出界
  528. endX = Math.max(0, Math.min(mouseX, imgWidth));
  529. endY = Math.max(0, Math.min(mouseY, imgHeight));
  530. drawAll();
  531. } else if (selectedBoxIndex !== -1 && dragMode) {
  532. let box = boxes[selectedBoxIndex];
  533. let minW = 10, minH = 10;
  534. let x = box.x, y = box.y, w = box.w, h = box.h;
  535. if (dragMode === 'move') {
  536. // 拖动移动框
  537. let newX = mouseX - dragOffsetX;
  538. let newY = mouseY - dragOffsetY;
  539. newX = Math.max(0, Math.min(newX, imgWidth - w));
  540. newY = Math.max(0, Math.min(newY, imgHeight - h));
  541. box.x = newX;
  542. box.y = newY;
  543. } else if (dragMode === 'resize' && resizeHandle) {
  544. // 8方向缩放
  545. switch (resizeHandle) {
  546. case 'nw': // 左上角
  547. box.x = Math.min(mouseX, x + w - minW);
  548. box.y = Math.min(mouseY, y + h - minH);
  549. box.w = w + (x - box.x);
  550. box.h = h + (y - box.y);
  551. break;
  552. case 'n': // 上中
  553. box.y = Math.min(mouseY, y + h - minH);
  554. box.h = h + (y - box.y);
  555. break;
  556. case 'ne': // 右上角
  557. box.y = Math.min(mouseY, y + h - minH);
  558. box.w = Math.max(minW, mouseX - x);
  559. box.h = h + (y - box.y);
  560. break;
  561. case 'e': // 右中
  562. box.w = Math.max(minW, mouseX - x);
  563. break;
  564. case 'se': // 右下角
  565. box.w = Math.max(minW, mouseX - x);
  566. box.h = Math.max(minH, mouseY - y);
  567. break;
  568. case 's': // 下中
  569. box.h = Math.max(minH, mouseY - y);
  570. break;
  571. case 'sw': // 左下角
  572. box.x = Math.min(mouseX, x + w - minW);
  573. box.w = w + (x - box.x);
  574. box.h = Math.max(minH, mouseY - y);
  575. break;
  576. case 'w': // 左中
  577. box.x = Math.min(mouseX, x + w - minW);
  578. box.w = w + (x - box.x);
  579. break;
  580. }
  581. // 限制不出界
  582. if (box.x < 0) { box.w += box.x; box.x = 0; }
  583. if (box.y < 0) { box.h += box.y; box.y = 0; }
  584. if (box.x + box.w > imgWidth) box.w = imgWidth - box.x;
  585. if (box.y + box.h > imgHeight) box.h = imgHeight - box.y;
  586. }
  587. drawAll();
  588. updateBoxesList();
  589. } else if (selectedBoxIndex !== -1) {
  590. // 悬停手柄时改变鼠标样式
  591. const box = boxes[selectedBoxIndex];
  592. const handleType = getHandleAt(mouseX, mouseY, box);
  593. setCursorByHandle(handleType);
  594. } else {
  595. $('#canvas').css('cursor', 'crosshair');
  596. }
  597. });
  598. // 鼠标松开事件
  599. $(document).on('mouseup', function(e) {
  600. if (isPanning) {
  601. isPanning = false;
  602. $('#canvas').css('cursor', spacePressed ? 'grab' : 'crosshair');
  603. return;
  604. }
  605. const rect = $('#canvas')[0].getBoundingClientRect();
  606. const canvasX = e.clientX - rect.left;
  607. const canvasY = e.clientY - rect.top;
  608. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  609. if (drawing) {
  610. drawing = false;
  611. // 重新用toImageCoord获取endX、endY,保证为图片原始坐标
  612. endX = Math.max(0, Math.min(mouseX, imgWidth));
  613. endY = Math.max(0, Math.min(mouseY, imgHeight));
  614. const x = Math.max(0, Math.min(startX, endX));
  615. const y = Math.max(0, Math.min(startY, endY));
  616. let w = Math.abs(endX - startX);
  617. let h = Math.abs(endY - startY);
  618. // 再次限制宽高不超界
  619. if (x + w > imgWidth) w = imgWidth - x;
  620. if (y + h > imgHeight) h = imgHeight - y;
  621. if (w > 5 && h > 5) {
  622. boxes.push({ x, y, w, h, classId: 0 });
  623. }
  624. drawAll();
  625. updateBoxesList();
  626. }
  627. // 鼠标松开后,始终清空拖动/缩放状态
  628. dragMode = null;
  629. resizeHandle = null;
  630. });
  631. // 删除按钮事件
  632. $('#boxes-list').on('click', '.del-btn', function() {
  633. const idx = $(this).data('idx');
  634. boxes.splice(idx, 1);
  635. if (selectedBoxIndex === idx) selectedBoxIndex = -1;
  636. drawAll();
  637. updateBoxesList();
  638. });
  639. // 右侧标注项点击选中,联动canvas高亮
  640. $('#boxes-list').on('click', '.box-item', function(e) {
  641. // 避免点击删除按钮时触发
  642. if ($(e.target).hasClass('del-btn')) return;
  643. const idx = $(this).index();
  644. selectedBoxIndex = idx;
  645. drawAll();
  646. updateBoxesList();
  647. });
  648. // -------------------- 导出/清空/缩放/切换图片等事件 --------------------
  649. // 导出YOLO格式标注
  650. $('#exportBtn').on('click', function() {
  651. // YOLO格式: class x_center y_center width height (均为归一化)
  652. let lines = boxes.map(box => {
  653. const x_center = (box.x + box.w / 2) / imgWidth;
  654. const y_center = (box.y + box.h / 2) / imgHeight;
  655. const w = box.w / imgWidth;
  656. const h = box.h / imgHeight;
  657. return `${box.classId} ${x_center} ${y_center} ${w} ${h}`;
  658. });
  659. const blob = new Blob([lines.join('\n')], { type: 'text/plain' });
  660. const a = document.createElement('a');
  661. a.href = URL.createObjectURL(blob);
  662. a.download = 'labels.txt';
  663. a.click();
  664. });
  665. // 清空所有标记按钮
  666. $('#clearBoxesBtn').on('click', function() {
  667. boxes = [];
  668. drawAll();
  669. updateBoxesList();
  670. });
  671. // 放大缩小按钮事件
  672. $('#zoomInBtn').on('click', function() {
  673. imgScale = Math.min(maxImgScale, imgScale * 1.2);
  674. drawAll();
  675. });
  676. $('#zoomOutBtn').on('click', function() {
  677. imgScale = Math.max(minImgScale, imgScale / 1.2);
  678. drawAll();
  679. });
  680. $('#zoomResetBtn').on('click', function() {
  681. imgScale = baseScale;
  682. imgOffsetX = 0;
  683. imgOffsetY = 0;
  684. drawAll();
  685. });
  686. // 鼠标滚轮缩放(以鼠标为中心)
  687. $('#canvas').on('wheel', function(e) {
  688. e.preventDefault();
  689. let mouseX = e.offsetX, mouseY = e.offsetY;
  690. // 1. 记录缩放前鼠标在图片上的坐标
  691. let before = toImageCoord(mouseX, mouseY);
  692. // 2. 计算缩放
  693. if (e.originalEvent.deltaY < 0) {
  694. imgScale = Math.min(maxImgScale, imgScale * 1.1);
  695. } else {
  696. imgScale = Math.max(minImgScale, imgScale / 1.1);
  697. }
  698. // 3. 计算缩放后该点在canvas上的新位置
  699. let after = toCanvasCoord(before.x, before.y);
  700. // 4. 调整offset,使鼠标下的图片点不动
  701. imgOffsetX += (mouseX - after.x);
  702. imgOffsetY += (mouseY - after.y);
  703. drawAll();
  704. });
  705. // 禁止右键菜单弹出
  706. $('#canvas').on('contextmenu', function(e) { e.preventDefault(); });
  707. // 鼠标移出canvas时隐藏坐标提示
  708. $('#canvas').on('mouseleave', function() {
  709. $('#coordTip').hide();
  710. });
  711. // 按钮切换上一张/下一张图片
  712. $('#prevImgBtn').on('click', function() {
  713. if (currentImgIndex > 0) {
  714. currentImgIndex--;
  715. renderImgList();
  716. loadCurrentImage();
  717. }
  718. });
  719. $('#nextImgBtn').on('click', function() {
  720. if (currentImgIndex < imgUrlArr.length - 1) {
  721. currentImgIndex++;
  722. renderImgList();
  723. loadCurrentImage();
  724. }
  725. });
  726. });
  727. </script>
  728. </body>
  729. </html>