html5画线需先调用beginpath(),再moveto()、lineto()和stroke();fetch post要设对content-type;localstorage存对象须json.stringify且避免循环引用;flex的flex:1在旧safari需写全。

HTML5 的 <canvas></canvas> 怎么画一条线?别漏掉 beginPath()
不调用 beginPath(),多次绘图会累积路径,导致意外重绘或性能下降。比如连续两次 stroke(),第二次会把第一次的线再描一遍。
- 必须先
ctx.beginPath(),再ctx.moveTo()和ctx.lineTo() -
ctx.stroke()只描当前路径,不自动清空;下次绘图前不beginPath(),旧路径还在 - 移动端 Safari 对未闭合路径的抗锯齿处理较弱,线条边缘容易发虚,加
ctx.lineCap = 'round'有改善
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath(); // 关键!
ctx.moveTo(10, 10);
ctx.lineTo(100, 100);
ctx.stroke();
用 fetch() 发 POST 请求,Content-Type 设错就 400
后端(尤其 Express、Django、Spring Boot)默认只解析 application/json 或 application/x-www-form-urlencoded,其他类型直接拒收。
- 传 JSON:必须设
headers: { 'Content-Type': 'application/json' },且body: JSON.stringify(data) - 传表单数据:用
new URLSearchParams(formObj),Content-Type由浏览器自动设为application/x-www-form-urlencoded,别手动覆盖 - 上传文件用
FormData,此时不能设Content-Type—— 浏览器要自动生成带 boundary 的 multipart 类型,手动设反而会破坏格式
localStorage 存对象报错 TypeError: Converting circular structure to JSON
因为 localStorage.setItem() 只接受字符串,而 JSON.stringify() 遇到循环引用(比如 DOM 元素、函数、互相引用的对象)就会崩。
- 常见踩坑:直接存
localStorage.setItem('user', userObj),其中userObj含ref或__proto__ - 安全做法:只存明确字段,如
localStorage.setItem('user', JSON.stringify({ id: u.id, name: u.name })) - 调试时可用
console.log(JSON.stringify(obj, null, 2))快速暴露循环引用点 - 需要存复杂状态?换
sessionStorage不解决根本问题,考虑用structuredClone()(Chrome 98+)配合内存缓存,而非硬塞 localStorage
Flex 布局中 flex: 1 在 Safari 15.6 之前不支持缩写语法
老版 Safari 把 flex: 1 解析成 flex: 1 1 0%,但实际行为是等同于 flex: 1 1 0px,导致内容溢出或高度塌陷。
立即学习“前端免费学习笔记(深入)”;
- 兼容写法:显式写全
flex: 1 1 0px或flex: 1 1 auto - 如果子项含图片或文字,
0%在某些 Safari 版本下会误判为不可伸缩,0px更稳 - 现代项目若已放弃 Safari ≤15.6,可放心用
flex: 1,但 CI 中的 E2E 测试仍可能跑在旧 WebKit 环境里,别只信本地 Chrome
fetch() 缺少 catch() 导致静默失败,以及 localStorage 里塞了没清理的调试数据把配额撑爆——这两处没错误提示,查起来最费时间。










