在线开发工具集

一站式开发解决方案,支持代码处理、编码转换、颜色操作和文本处理

高效 安全 便捷

代码工具

格式化、压缩和美化您的CSS、JS和HTML代码

格式化
压缩
美化
开始使用

编码工具

Base64和URL编码/解码,保护您的数据安全

Base64
URL编码
解码
开始使用

JSON工具

JSON格式化、验证和压缩

格式化
验证
压缩
开始使用

正则工具

正则表达式测试和生成

测试
生成
匹配
开始使用

颜色工具

颜色选择、格式转换和调色板生成

HEX
RGB
HSL
开始使用

渐变工具

CSS渐变色生成和预览

线性渐变
径向渐变
CSS代码
开始使用

文本工具

大小写转换、文本反转和空格处理

大写
小写
反转
开始使用

图片工具

图片格式转换、压缩和调整大小

格式转换
压缩
调整大小
开始使用

代码工具

格式化、压缩和美化您的代码

输入代码

1

输出代码

1
0
输入字符
0
输出字符
0%
压缩率

编码工具

Base64和URL编码/解码

输入文本

输出结果

颜色工具

颜色选择、格式转换和调色板

颜色选择器

颜色格式

颜色预览

示例文本

调色板

文本工具

文本处理和转换工具

输入文本

文本统计

0
字符数
0
单词数
0
行数

输出文本

文本操作

JSON工具

JSON格式化、验证和压缩

输入JSON

1

输出JSON

1
0
输入字符
0
输出字符
等待
状态

正则工具

正则表达式测试和生成

输入文本

匹配结果

1
0
匹配数量
未测试
测试结果
g
匹配模式

常用正则表达式

图片工具

图片格式转换、压缩和调整大小

上传图片

点击或拖拽图片到此处

图片信息

-
宽度
-
高度
-
大小

图片预览

图片预览将显示在这里

80%
×

渐变工具

CSS渐变色生成和预览

渐变配置

渐变预览

CSS代码

1

预设渐变

操作成功
您的操作已成功完成
`; } inputCode.value = sampleCode; updateStats(); showNotification('示例加载', '示例代码已加载'); } // 复制输出代码 function copyOutputCode() { if (outputCode.value) { outputCode.select(); navigator.clipboard.writeText(outputCode.value).then(function() { showNotification('复制成功', '代码已复制到剪贴板'); }).catch(function() { document.execCommand('copy'); showNotification('复制成功', '代码已复制到剪贴板'); }); } else { showNotification('操作失败', '没有可复制的代码', true); } } // 下载输出代码 function downloadOutputCode() { if (outputCode.value) { const codeType = document.getElementById('codeType').value; const extension = codeType === 'css' ? 'css' : codeType === 'js' ? 'js' : 'html'; const blob = new Blob([outputCode.value], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `code.${extension}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showNotification('下载成功', '代码已下载'); } else { showNotification('操作失败', '没有可下载的代码', true); } } // 事件监听 inputCode.addEventListener('input', updateStats); formatBtn.addEventListener('click', formatCode); compressBtn.addEventListener('click', compressCode); beautifyBtn.addEventListener('click', beautifyCode); loadSample.addEventListener('click', loadSampleCode); clearInput.addEventListener('click', function() { inputCode.value = ''; outputCode.value = ''; updateStats(); showNotification('清空完成', '输入已清空'); }); copyOutput.addEventListener('click', copyOutputCode); downloadOutput.addEventListener('click', downloadOutputCode); // 初始化 updateStats(); console.log('代码工具初始化完成'); } // 编码工具功能 function initializeEncodeTool() { console.log('初始化编码工具...'); const encodeInput = document.getElementById('encodeInput'); const encodeOutput = document.getElementById('encodeOutput'); const encodeBase64Btn = document.getElementById('encodeBase64Btn'); const decodeBase64Btn = document.getElementById('decodeBase64Btn'); const encodeURLBtn = document.getElementById('encodeURLBtn'); const decodeURLBtn = document.getElementById('decodeURLBtn'); const copyEncodeBtn = document.getElementById('copyEncodeBtn'); const clearEncodeBtn = document.getElementById('clearEncodeBtn'); if (!encodeInput || !encodeOutput) { console.error('编码工具元素未找到'); return; } // Base64编码 function encodeBase64() { try { const encoded = btoa(unescape(encodeURIComponent(encodeInput.value))); encodeOutput.value = encoded; showNotification('编码完成', '文本已Base64编码'); } catch (e) { showNotification('编码失败', '编码过程中出现错误', true); } } // Base64解码 function decodeBase64() { try { const decoded = decodeURIComponent(escape(atob(encodeInput.value))); encodeOutput.value = decoded; showNotification('解码完成', '文本已Base64解码'); } catch (e) { showNotification('解码失败', '解码过程中出现错误', true); } } // URL编码 function encodeURL() { try { const encoded = encodeURIComponent(encodeInput.value); encodeOutput.value = encoded; showNotification('编码完成', '文本已URL编码'); } catch (e) { showNotification('编码失败', '编码过程中出现错误', true); } } // URL解码 function decodeURL() { try { const decoded = decodeURIComponent(encodeInput.value); encodeOutput.value = decoded; showNotification('解码完成', '文本已URL解码'); } catch (e) { showNotification('解码失败', '解码过程中出现错误', true); } } // 复制结果 function copyEncodeResult() { if (encodeOutput.value) { encodeOutput.select(); navigator.clipboard.writeText(encodeOutput.value).then(function() { showNotification('复制成功', '结果已复制到剪贴板'); }).catch(function() { document.execCommand('copy'); showNotification('复制成功', '结果已复制到剪贴板'); }); } else { showNotification('操作失败', '没有可复制的结果', true); } } // 清空所有 function clearEncodeAll() { encodeInput.value = ''; encodeOutput.value = ''; showNotification('清空完成', '所有内容已清空'); } // 事件监听 encodeBase64Btn.addEventListener('click', encodeBase64); decodeBase64Btn.addEventListener('click', decodeBase64); encodeURLBtn.addEventListener('click', encodeURL); decodeURLBtn.addEventListener('click', decodeURL); copyEncodeBtn.addEventListener('click', copyEncodeResult); clearEncodeBtn.addEventListener('click', clearEncodeAll); console.log('编码工具初始化完成'); } // 颜色工具功能 function initializeColorTool() { console.log('初始化颜色工具...'); const colorPicker = document.getElementById('colorPicker'); const hexValue = document.getElementById('hexValue'); const rgbValue = document.getElementById('rgbValue'); const hslValue = document.getElementById('hslValue'); const colorPreview = document.getElementById('colorPreview'); const colorSwatches = document.querySelectorAll('.color-swatch'); if (!colorPicker || !hexValue) { console.error('颜色工具元素未找到'); return; } // 更新颜色值 function updateColorValues(color) { hexValue.value = color; // HEX转RGB const r = parseInt(color.substr(1, 2), 16); const g = parseInt(color.substr(3, 2), 16); const b = parseInt(color.substr(5, 2), 16); rgbValue.value = `rgb(${r}, ${g}, ${b})`; // RGB转HSL const hsl = rgbToHsl(r, g, b); hslValue.value = `hsl(${Math.round(hsl.h)}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)`; // 更新预览 colorPreview.style.backgroundColor = color; } // RGB转HSL function rgbToHsl(r, g, b) { r /= 255; g /= 255; b /= 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max === min) { h = s = 0; // 灰色 } else { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s * 100, l: l * 100 }; } // 颜色选择器变化 colorPicker.addEventListener('input', function() { updateColorValues(this.value); }); // HEX值变化 hexValue.addEventListener('input', function() { const color = this.value; if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(color)) { colorPicker.value = color.length === 4 ? `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}` : color; updateColorValues(colorPicker.value); } }); // RGB值变化 - 修复语法错误 rgbValue.addEventListener('input', function() { const match = this.value.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/); if (match) { const r = parseInt(match[1]); const g = parseInt(match[2]); const b = parseInt(match[3]); const hex = `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`; colorPicker.value = hex; updateColorValues(hex); } }); // 修复了缺少的结束括号 // 颜色样本点击 colorSwatches.forEach(swatch => { swatch.addEventListener('click', function() { const color = this.getAttribute('data-color'); colorPicker.value = color; updateColorValues(color); showNotification('颜色选择', '颜色已应用'); }); }); // 初始化 updateColorValues(colorPicker.value); console.log('颜色工具初始化完成'); } // 文本工具功能 function initializeTextTool() { console.log('初始化文本工具...'); const textInput = document.getElementById('textInput'); const textOutput = document.getElementById('textOutput'); const charCount = document.getElementById('charCount'); const wordCount = document.getElementById('wordCount'); const lineCount = document.getElementById('lineCount'); const toUpperCaseBtn = document.getElementById('toUpperCaseBtn'); const toLowerCaseBtn = document.getElementById('toLowerCaseBtn'); const capitalizeBtn = document.getElementById('capitalizeBtn'); const reverseTextBtn = document.getElementById('reverseTextBtn'); const removeSpacesBtn = document.getElementById('removeSpacesBtn'); const clearTextBtn = document.getElementById('clearTextBtn'); if (!textInput || !textOutput) { console.error('文本工具元素未找到'); return; } // 更新文本统计 function updateTextStats() { const text = textInput.value; charCount.textContent = text.length; wordCount.textContent = text.trim() ? text.trim().split(/\s+/).length : 0; lineCount.textContent = text ? text.split('\n').length : 0; } // 转为大写 function toUpperCase() { textOutput.value = textInput.value.toUpperCase(); showNotification('转换完成', '文本已转为大写'); } // 转为小写 function toLowerCase() { textOutput.value = textInput.value.toLowerCase(); showNotification('转换完成', '文本已转为小写'); } // 首字母大写 function capitalize() { textOutput.value = textInput.value.replace(/\b\w/g, l => l.toUpperCase()); showNotification('转换完成', '文本首字母已大写'); } // 反转文本 function reverseText() { textOutput.value = textInput.value.split('').reverse().join(''); showNotification('转换完成', '文本已反转'); } // 移除空格 function removeSpaces() { textOutput.value = textInput.value.replace(/\s+/g, ''); showNotification('转换完成', '空格已移除'); } // 清空文本 function clearText() { textInput.value = ''; textOutput.value = ''; updateTextStats(); showNotification('清空完成', '文本已清空'); } // 事件监听 textInput.addEventListener('input', updateTextStats); toUpperCaseBtn.addEventListener('click', toUpperCase); toLowerCaseBtn.addEventListener('click', toLowerCase); capitalizeBtn.addEventListener('click', capitalize); reverseTextBtn.addEventListener('click', reverseText); removeSpacesBtn.addEventListener('click', removeSpaces); clearTextBtn.addEventListener('click', clearText); // 初始化 updateTextStats(); console.log('文本工具初始化完成'); } // JSON工具功能 function initializeJsonTool() { console.log('初始化JSON工具...'); const jsonInput = document.getElementById('jsonInput'); const jsonOutput = document.getElementById('jsonOutput'); const jsonInputChars = document.getElementById('jsonInputChars'); const jsonOutputChars = document.getElementById('jsonOutputChars'); const jsonStatus = document.getElementById('jsonStatus'); const loadJsonSample = document.getElementById('loadJsonSample'); const clearJsonInput = document.getElementById('clearJsonInput'); const copyJsonBtn = document.getElementById('copyJsonBtn'); const validateJsonBtn = document.getElementById('validateJsonBtn'); const formatJsonBtn = document.getElementById('formatJsonBtn'); const compressJsonBtn = document.getElementById('compressJsonBtn'); const escapeJsonBtn = document.getElementById('escapeJsonBtn'); const unescapeJsonBtn = document.getElementById('unescapeJsonBtn'); if (!jsonInput || !jsonOutput) { console.error('JSON工具元素未找到'); return; } // 更新JSON统计 function updateJsonStats() { jsonInputChars.textContent = jsonInput.value.length; jsonOutputChars.textContent = jsonOutput.value.length; // 更新行号 updateJsonLineNumbers('jsonInputLineNumbers', jsonInput); updateJsonLineNumbers('jsonOutputLineNumbers', jsonOutput); } // 更新行号 function updateJsonLineNumbers(lineNumbersId, textarea) { const lineNumbers = document.getElementById(lineNumbersId); if (!lineNumbers) return; const lines = textarea.value.split('\n').length; let numbersHtml = ''; for (let i = 1; i <= lines; i++) { numbersHtml += i + '
'; } lineNumbers.innerHTML = numbersHtml; } // 格式化JSON function formatJson() { try { const obj = JSON.parse(jsonInput.value); jsonOutput.value = JSON.stringify(obj, null, 2); jsonStatus.textContent = '有效'; jsonStatus.style.color = 'var(--success-color)'; showNotification('格式化完成', 'JSON已格式化'); } catch (e) { jsonStatus.textContent = '无效'; jsonStatus.style.color = 'var(--accent-color)'; showNotification('格式化失败', 'JSON格式无效', true); } updateJsonStats(); } // 压缩JSON function compressJson() { try { const obj = JSON.parse(jsonInput.value); jsonOutput.value = JSON.stringify(obj); jsonStatus.textContent = '有效'; jsonStatus.style.color = 'var(--success-color)'; showNotification('压缩完成', 'JSON已压缩'); } catch (e) { jsonStatus.textContent = '无效'; jsonStatus.style.color = 'var(--accent-color)'; showNotification('压缩失败', 'JSON格式无效', true); } updateJsonStats(); } // 验证JSON function validateJson() { try { JSON.parse(jsonInput.value); jsonStatus.textContent = '有效'; jsonStatus.style.color = 'var(--success-color)'; showNotification('验证通过', 'JSON格式有效'); } catch (e) { jsonStatus.textContent = '无效'; jsonStatus.style.color = 'var(--accent-color)'; showNotification('验证失败', 'JSON格式无效: ' + e.message, true); } } // 转义JSON function escapeJson() { jsonOutput.value = JSON.stringify(jsonInput.value); jsonStatus.textContent = '已转义'; showNotification('转义完成', 'JSON已转义'); updateJsonStats(); } // 反转义JSON function unescapeJson() { try { jsonOutput.value = JSON.parse(jsonInput.value); jsonStatus.textContent = '已反转义'; showNotification('反转义完成', 'JSON已反转义'); } catch (e) { jsonStatus.textContent = '无效'; jsonStatus.style.color = 'var(--accent-color)'; showNotification('反转义失败', 'JSON格式无效', true); } updateJsonStats(); } // 加载示例JSON function loadJsonSampleCode() { const sampleJson = `{ "name": "示例项目", "version": "1.0.0", "description": "这是一个示例JSON数据", "author": { "name": "张三", "email": "zhangsan@example.com" }, "keywords": ["示例", "JSON", "数据"], "dependencies": { "express": "^4.18.0", "mongoose": "^6.0.0" }, "scripts": { "start": "node app.js", "dev": "nodemon app.js" } }`; jsonInput.value = sampleJson; updateJsonStats(); showNotification('示例加载', '示例JSON已加载'); } // 复制JSON function copyJson() { if (jsonOutput.value) { jsonOutput.select(); navigator.clipboard.writeText(jsonOutput.value).then(function() { showNotification('复制成功', 'JSON已复制到剪贴板'); }).catch(function() { document.execCommand('copy'); showNotification('复制成功', 'JSON已复制到剪贴板'); }); } else { showNotification('操作失败', '没有可复制的JSON', true); } } // 事件监听 jsonInput.addEventListener('input', updateJsonStats); formatJsonBtn.addEventListener('click', formatJson); compressJsonBtn.addEventListener('click', compressJson); validateJsonBtn.addEventListener('click', validateJson); escapeJsonBtn.addEventListener('click', escapeJson); unescapeJsonBtn.addEventListener('click', unescapeJson); loadJsonSample.addEventListener('click', loadJsonSampleCode); clearJsonInput.addEventListener('click', function() { jsonInput.value = ''; jsonOutput.value = ''; jsonStatus.textContent = '等待'; jsonStatus.style.color = 'var(--dark-color)'; updateJsonStats(); showNotification('清空完成', 'JSON已清空'); }); copyJsonBtn.addEventListener('click', copyJson); // 初始化 updateJsonStats(); console.log('JSON工具初始化完成'); } // 正则工具功能 function initializeRegexTool() { console.log('初始化正则工具...'); const regexPattern = document.getElementById('regexPattern'); const regexTestText = document.getElementById('regexTestText'); const regexInput = document.getElementById('regexInput'); const regexOutput = document.getElementById('regexOutput'); const regexMatchCount = document.getElementById('regexMatchCount'); const regexTestResult = document.getElementById('regexTestResult'); const regexFlags = document.getElementById('regexFlags'); const testRegexBtn = document.getElementById('testRegexBtn'); const matchRegexBtn = document.getElementById('matchRegexBtn'); const clearRegexBtn = document.getElementById('clearRegexBtn'); const commonRegexButtons = document.querySelectorAll('[data-regex]'); if (!regexPattern || !regexInput) { console.error('正则工具元素未找到'); return; } // 测试正则表达式 function testRegex() { const pattern = regexPattern.value; const testText = regexTestText.value; if (!pattern) { showNotification('测试失败', '请输入正则表达式', true); return; } try { const regex = new RegExp(pattern, 'g'); const result = regex.test(testText); regexTestResult.textContent = result ? '匹配' : '不匹配'; regexTestResult.style.color = result ? 'var(--success-color)' : 'var(--accent-color)'; showNotification('测试完成', result ? '正则表达式匹配成功' : '正则表达式不匹配'); } catch (e) { regexTestResult.textContent = '错误'; regexTestResult.style.color = 'var(--accent-color)'; showNotification('测试失败', '正则表达式格式错误: ' + e.message, true); } } // 执行匹配 function matchRegex() { const pattern = regexPattern.value; const inputText = regexInput.value; if (!pattern) { showNotification('匹配失败', '请输入正则表达式', true); return; } try { const regex = new RegExp(pattern, 'g'); const matches = inputText.match(regex) || []; regexMatchCount.textContent = matches.length; // 显示匹配结果 if (matches.length > 0) { regexOutput.value = matches.join('\n'); } else { regexOutput.value = '没有找到匹配项'; } // 更新行号 updateRegexLineNumbers(); showNotification('匹配完成', `找到 ${matches.length} 个匹配项`); } catch (e) { regexOutput.value = '正则表达式错误: ' + e.message; regexMatchCount.textContent = '0'; showNotification('匹配失败', '正则表达式格式错误: ' + e.message, true); } } // 更新行号 function updateRegexLineNumbers() { const lineNumbers = document.getElementById('regexOutputLineNumbers'); if (!lineNumbers) return; const lines = regexOutput.value.split('\n').length; let numbersHtml = ''; for (let i = 1; i <= lines; i++) { numbersHtml += i + '
'; } lineNumbers.innerHTML = numbersHtml; } // 清空所有 function clearRegexAll() { regexPattern.value = ''; regexTestText.value = ''; regexInput.value = ''; regexOutput.value = ''; regexMatchCount.textContent = '0'; regexTestResult.textContent = '未测试'; regexTestResult.style.color = 'var(--dark-color)'; updateRegexLineNumbers(); showNotification('清空完成', '所有内容已清空'); } // 常用正则表达式 commonRegexButtons.forEach(button => { button.addEventListener('click', function() { regexPattern.value = this.getAttribute('data-regex'); showNotification('预设加载', '正则表达式已加载'); }); }); // 事件监听 testRegexBtn.addEventListener('click', testRegex); matchRegexBtn.addEventListener('click', matchRegex); clearRegexBtn.addEventListener('click', clearRegexAll); // 初始化 updateRegexLineNumbers(); console.log('正则工具初始化完成'); } // 图片工具功能 function initializeImageTool() { console.log('初始化图片工具...'); const uploadArea = document.getElementById('uploadArea'); const imageUpload = document.getElementById('imageUpload'); const selectImageBtn = document.getElementById('selectImageBtn'); const clearImageBtn = document.getElementById('clearImageBtn'); const imagePreview = document.getElementById('imagePreview'); const downloadImageBtn = document.getElementById('downloadImageBtn'); const copyImageBtn = document.getElementById('copyImageBtn'); const imageFormat = document.getElementById('imageFormat'); const imageQuality = document.getElementById('imageQuality'); const qualityValue = document.getElementById('qualityValue'); const resizeWidth = document.getElementById('resizeWidth'); const resizeHeight = document.getElementById('resizeHeight'); const keepAspectRatio = document.getElementById('keepAspectRatio'); const convertImageBtn = document.getElementById('convertImageBtn'); const compressImageBtn = document.getElementById('compressImageBtn'); const resizeImageBtn = document.getElementById('resizeImageBtn'); const imageWidth = document.getElementById('imageWidth'); const imageHeight = document.getElementById('imageHeight'); const imageSize = document.getElementById('imageSize'); if (!uploadArea || !imageUpload) { console.error('图片工具元素未找到'); return; } let currentImage = null; let originalImage = null; // 选择图片按钮点击事件 selectImageBtn.addEventListener('click', function() { imageUpload.click(); }); // 上传区域点击事件 uploadArea.addEventListener('click', function() { imageUpload.click(); }); // 文件选择变化事件 imageUpload.addEventListener('change', function(e) { if (e.target.files && e.target.files[0]) { handleImageUpload(e.target.files[0]); } }); // 拖放事件 uploadArea.addEventListener('dragover', function(e) { e.preventDefault(); uploadArea.classList.add('dragover'); }); uploadArea.addEventListener('dragleave', function() { uploadArea.classList.remove('dragover'); }); uploadArea.addEventListener('drop', function(e) { e.preventDefault(); uploadArea.classList.remove('dragover'); if (e.dataTransfer.files && e.dataTransfer.files[0]) { handleImageUpload(e.dataTransfer.files[0]); } }); // 图片质量滑块事件 imageQuality.addEventListener('input', function() { qualityValue.textContent = this.value + '%'; }); // 保持宽高比事件 keepAspectRatio.addEventListener('change', function() { if (this.checked && originalImage && resizeWidth.value) { const ratio = originalImage.height / originalImage.width; resizeHeight.value = Math.round(resizeWidth.value * ratio); } }); // 宽度变化事件 resizeWidth.addEventListener('input', function() { if (keepAspectRatio.checked && originalImage && this.value) { const ratio = originalImage.height / originalImage.width; resizeHeight.value = Math.round(this.value * ratio); } }); // 清空图片按钮点击事件 clearImageBtn.addEventListener('click', function() { resetImageTool(); showNotification('清空完成', '图片已清空'); }); // 转换格式按钮点击事件 convertImageBtn.addEventListener('click', function() { if (!currentImage) return; const format = imageFormat.value; const quality = imageQuality.value / 100; convertImage(format, quality); }); // 压缩图片按钮点击事件 compressImageBtn.addEventListener('click', function() { if (!currentImage) return; const quality = imageQuality.value / 100; convertImage(imageFormat.value, quality); }); // 调整大小按钮点击事件 resizeImageBtn.addEventListener('click', function() { if (!currentImage) return; const width = parseInt(resizeWidth.value) || originalImage.width; const height = parseInt(resizeHeight.value) || originalImage.height; resizeImage(width, height); }); // 处理图片上传 function handleImageUpload(file) { if (!file.type.match('image.*')) { showNotification('上传失败', '请上传图片文件', true); return; } const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { originalImage = img; currentImage = img; // 显示图片预览 imagePreview.innerHTML = ''; const previewImg = document.createElement('img'); previewImg.src = e.target.result; previewImg.style.maxWidth = '100%'; previewImg.style.maxHeight = '100%'; imagePreview.appendChild(previewImg); // 更新图片信息 imageWidth.textContent = img.width + 'px'; imageHeight.textContent = img.height + 'px'; imageSize.textContent = formatFileSize(file.size); // 设置默认调整大小值 resizeWidth.value = img.width; resizeHeight.value = img.height; // 启用按钮 convertImageBtn.disabled = false; compressImageBtn.disabled = false; resizeImageBtn.disabled = false; downloadImageBtn.disabled = false; copyImageBtn.disabled = false; showNotification('上传成功', '图片已上传'); }; img.src = e.target.result; }; reader.readAsDataURL(file); } // 转换图片格式 function convertImage(format, quality) { const canvas = document.createElement('canvas'); canvas.width = originalImage.width; canvas.height = originalImage.height; const ctx = canvas.getContext('2d'); ctx.drawImage(originalImage, 0, 0); let mimeType; switch(format) { case 'jpeg': mimeType = 'image/jpeg'; break; case 'png': mimeType = 'image/png'; break; case 'webp': mimeType = 'image/webp'; break; case 'bmp': mimeType = 'image/bmp'; break; default: mimeType = 'image/png'; } const dataURL = canvas.toDataURL(mimeType, quality); // 更新预览 imagePreview.innerHTML = ''; const previewImg = document.createElement('img'); previewImg.src = dataURL; previewImg.style.maxWidth = '100%'; previewImg.style.maxHeight = '100%'; imagePreview.appendChild(previewImg); currentImage = previewImg; showNotification('转换完成', '图片格式已转换为 ' + format.toUpperCase()); } // 调整图片大小 function resizeImage(width, height) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(originalImage, 0, 0, width, height); const dataURL = canvas.toDataURL(); // 更新预览 imagePreview.innerHTML = ''; const previewImg = document.createElement('img'); previewImg.src = dataURL; previewImg.style.maxWidth = '100%'; previewImg.style.maxHeight = '100%'; imagePreview.appendChild(previewImg); currentImage = previewImg; // 更新图片信息 imageWidth.textContent = width + 'px'; imageHeight.textContent = height + 'px'; showNotification('调整完成', '图片大小已调整为 ' + width + '×' + height); } // 格式化文件大小 function formatFileSize(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } // 重置图片工具 function resetImageTool() { imageUpload.value = ''; imagePreview.innerHTML = `

图片预览将显示在这里

`; imageWidth.textContent = '-'; imageHeight.textContent = '-'; imageSize.textContent = '-'; resizeWidth.value = ''; resizeHeight.value = ''; convertImageBtn.disabled = true; compressImageBtn.disabled = true; resizeImageBtn.disabled = true; downloadImageBtn.disabled = true; copyImageBtn.disabled = true; currentImage = null; originalImage = null; } // 初始化图片工具 resetImageTool(); console.log('图片工具初始化完成'); } // 渐变工具功能 function initializeGradientTool() { console.log('初始化渐变工具...'); const gradientType = document.getElementById('gradientType'); const gradientDirection = document.getElementById('gradientDirection'); const colorStops = document.getElementById('colorStops'); const addColorStopBtn = document.getElementById('addColorStop'); const gradientPreview = document.getElementById('gradientPreview'); const gradientCode = document.getElementById('gradientCode'); const copyGradientBtn = document.getElementById('copyGradientBtn'); const downloadGradientBtn = document.getElementById('downloadGradientBtn'); const presetGradients = document.querySelectorAll('.preset-gradient'); if (!gradientType || !gradientPreview) { console.error('渐变工具元素未找到'); return; } // 添加颜色节点按钮点击事件 addColorStopBtn.addEventListener('click', function() { addColorStop('#ffffff', 50); }); // 渐变类型变化事件 gradientType.addEventListener('change', updateGradient); // 渐变方向变化事件 gradientDirection.addEventListener('change', updateGradient); // 复制代码按钮点击事件 copyGradientBtn.addEventListener('click', function() { if (gradientCode.value) { gradientCode.select(); navigator.clipboard.writeText(gradientCode.value).then(function() { showNotification('复制成功', 'CSS代码已复制到剪贴板'); }).catch(function() { document.execCommand('copy'); showNotification('复制成功', 'CSS代码已复制到剪贴板'); }); } else { showNotification('操作失败', '没有可复制的代码', true); } }); // 下载CSS按钮点击事件 downloadGradientBtn.addEventListener('click', function() { if (gradientCode.value) { const blob = new Blob([gradientCode.value], { type: 'text/css' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'gradient.css'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showNotification('下载成功', 'CSS代码已下载'); } else { showNotification('操作失败', '没有可下载的代码', true); } }); // 预设渐变点击事件 presetGradients.forEach(preset => { preset.addEventListener('click', function() { const gradient = this.getAttribute('data-gradient'); applyPresetGradient(gradient); }); }); // 添加颜色节点 function addColorStop(color, position) { const colorStopItem = document.createElement('div'); colorStopItem.className = 'color-stop-item mb-2'; colorStopItem.innerHTML = `
`; colorStops.appendChild(colorStopItem); // 添加事件监听 const colorInput = colorStopItem.querySelector('input[type="color"]'); const positionInput = colorStopItem.querySelector('input[type="number"]'); const removeBtn = colorStopItem.querySelector('.remove-color-stop'); colorInput.addEventListener('input', updateGradient); positionInput.addEventListener('input', updateGradient); removeBtn.addEventListener('click', function() { colorStopItem.remove(); updateGradient(); }); updateGradient(); } // 更新渐变 function updateGradient() { const type = gradientType.value; const direction = gradientDirection.value; const colorStopItems = colorStops.querySelectorAll('.color-stop-item'); if (colorStopItems.length < 2) { showNotification('操作失败', '至少需要两个颜色节点', true); return; } let gradientString; let colorStopsArray = []; // 收集颜色节点 colorStopItems.forEach(item => { const color = item.querySelector('input[type="color"]').value; const position = item.querySelector('input[type="number"]').value; colorStopsArray.push(`${color} ${position}%`); }); // 构建渐变字符串 if (type === 'linear') { gradientString = `linear-gradient(${direction}, ${colorStopsArray.join(', ')})`; } else { gradientString = `radial-gradient(${direction}, ${colorStopsArray.join(', ')})`; } // 更新预览 gradientPreview.style.background = gradientString; // 更新CSS代码 gradientCode.value = `background: ${gradientString};`; // 更新行号 updateGradientLineNumbers(); } // 应用预设渐变 function applyPresetGradient(gradient) { // 解析预设渐变 const isLinear = gradient.startsWith('linear-gradient'); const isRadial = gradient.startsWith('radial-gradient'); if (isLinear) { gradientType.value = 'linear'; // 提取方向 const directionMatch = gradient.match(/linear-gradient\(([^,]+),/); if (directionMatch) { gradientDirection.value = directionMatch[1].trim(); } } else if (isRadial) { gradientType.value = 'radial'; // 提取形状 const shapeMatch = gradient.match(/radial-gradient\(([^,]+),/); if (shapeMatch) { gradientDirection.value = shapeMatch[1].trim(); } } // 提取颜色节点 const colorStopsMatch = gradient.match(/linear-gradient\([^)]+\)|radial-gradient\([^)]+\)/); if (colorStopsMatch) { const fullGradient = colorStopsMatch[0]; const colorsPart = fullGradient.substring(fullGradient.indexOf('(') + 1, fullGradient.lastIndexOf(')')); const colorsArray = colorsPart.split(',').slice(1); // 去掉方向部分 // 清空现有颜色节点 colorStops.innerHTML = ''; // 添加新的颜色节点 colorsArray.forEach((colorStop, index) => { const colorStopTrimmed = colorStop.trim(); const colorMatch = colorStopTrimmed.match(/(#[0-9a-fA-F]+|rgb\([^)]+\)|rgba\([^)]+\)|hsl\([^)]+\)|hsla\([^)]+\))\s*(\d+%)?/); if (colorMatch) { const color = colorMatch[1]; let position = colorMatch[2] ? parseInt(colorMatch[2]) : (index / (colorsArray.length - 1)) * 100; // 如果是第一个节点,位置为0% if (index === 0) position = 0; // 如果是最后一个节点,位置为100% if (index === colorsArray.length - 1) position = 100; addColorStop(color, position); } }); } updateGradient(); showNotification('预设加载', '预设渐变已应用'); } // 更新渐变行号 function updateGradientLineNumbers() { const lineNumbers = document.getElementById('gradientLineNumbers'); if (!lineNumbers) return; const lines = gradientCode.value.split('\n').length; let numbersHtml = ''; for (let i = 1; i <= lines; i++) { numbersHtml += i + '
'; } lineNumbers.innerHTML = numbersHtml; } // 初始化渐变工具 updateGradient(); console.log('渐变工具初始化完成'); }