蓝色天空网mbsky.com · 知识 · 实践 · 创造Claude Code · 本地阅读预览
教程 / AI / 智能开发 / Claude Code

Claude Code 实战:制作新闻卡片生成器

从明确的交互要求出发,构建可编辑、预览和导出 PNG 的中文新闻卡片。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先定义能验收的功能

本课以报纸式排版为灵感,做一张自有的城市简报卡片。卡片包含分类、标题、副标题、摘要、作者、日期和可选图片。版面采用衬线字体、墨色文字及强调线,配置和品牌素材均可自行调整。

给 Claude Code 描述验收条件,包括修改字段时预览立即更新,鼠标选择和拖放都可载入图片,PNG 必须为 1200×630,缩小窗口后编辑与预览按单列排列。开发过程可让工具创建文件,也可以让它先输出命令和修改计划。

初始化并锁定项目

从新工作目录启动 CLI。在项目启动提示中明确 React、Tailwind 3、Vite 和 html2canvas 的版本,避免混用 Tailwind 3 的 PostCSS 与另一主版本的接入方式。用包清单和锁文件分别记录直接与传递依赖。

执行命令前核对目标目录、写入和网络范围。分阶段审查安装、文件改动与构建结果。本站练习将依赖固定在独立工程,不使用现有站点的编辑页面和发布数据。

把入口、编辑器状态、预览卡片和导出过程分开看。本站将这些组件写在 src/main.jsx,样式和扫描规则分别由 src/index.css、tailwind.config.js 与 postcss.config.js 管理。

Tailwind 扫描 HTML 和 JSX 中使用的类。把纸色、文字色、强调色与本地衬线字体写进 theme.extend。外部字体需要额外声明来源、授权与加载条件,本例通过系统字体回退离线运行。

在 CSS 入口包含 Tailwind 的 base、components 和 utilities 三层指令。用 Vite 实际构建验证扫描后的产物,生成的 JS 和 CSS 随源码一起提供于本地下载包。

编辑内容并检查实时预览

编辑器通过受控字段保存同一组数据。它和预览卡片共用状态,输入的中文文本会同步呈现在卡片。用显式标签关联确保标题、摘要和其它字段都能通过可访问名称找到。

在卡片里用分隔线、标题和正文体现层次。图片为空时文字区域自动占用可用宽度。图片预览接受 PNG、JPEG 或 WebP,经实际解码后才更新。点击选择或拖放走同一校验流程,非法数据保留现有图片。

添加城市、文化和交通三套预设。选择预设时填好所有文字字段,再让读者继续修改。先选文化预设,再改标题、摘要、作者和日期即可观察状态更新。

保存 1200×630 PNG

预览在窄屏内缩放,导出仍采用独立的固定 1200×630 CSS 画布。等待字体准备后用 html2canvas 构建位图,指定 scale 为 1,避免高像素密度屏幕得到双倍尺寸。

点击后显示进行中的状态并临时禁用按钮。生成 PNG Blob 后触发浏览器下载,解码后可核对尺寸、配图和纸张颜色。失败时在页面显示反馈。

下图是本站浏览器实测画面。可见自编中文内容、青绿色测试图和 PNG 已生成的状态。教学下载包含源码、构建配置、锁文件和本地站点产物。

中文城市简报编辑页面、青绿色配图和 PNG 已生成的提示
在本机浏览器实际编辑中文文本、上传配图并完成下载后捕获的本站页面。

试用中文编辑、预设、配图与 PNG 导出

jsx · 阅读源码
import React, { useLayoutEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import html2canvas from "html2canvas";
import "./index.css";

const templates = [
  { section: "城市", headline: "北岸步道重新开放", subhead: "沿河更新进入下一阶段", summary: "新的休息区已开放,周末增设城市步行导览。", author: "林初", date: "2027-03-19" },
  { section: "文化", headline: "春季书展本周开幕", subhead: "独立书店发布活动日程", summary: "书展集合本地作者分享、旧书交换及儿童读书会。", author: "周宁", date: "2027-03-20" },
  { section: "交通", headline: "夜间公交调整班次", subhead: "测试运行覆盖三个片区", summary: "公交服务将在下周延长末班车时间,以便夜间通勤。", author: "陈青", date: "2027-03-21" },
];
const fields = [
  ["section", "分类", 12], ["headline", "标题", 30], ["subhead", "副标题", 40],
  ["summary", "摘要", 104], ["author", "作者", 18], ["date", "日期", 10],
];

function NewsCard({ card, photo, style }) {
  return <article className="news-card bg-paper p-16 font-editorial" style={style}>
    <div className="border-b-4 border-accent pb-4 text-2xl">城市简报 · {card.section}</div>
    <div className="mt-10 flex items-start justify-between gap-12">
      <div className="min-w-0 flex-1">
        <h2 className="break-words text-[56px] font-bold leading-tight">{card.headline || "未填标题"}</h2>
        <p className="mt-4 break-words text-[30px] leading-snug">{card.subhead}</p>
        <p className="mt-6 break-words text-[25px] leading-snug text-[#504a3c]">{card.summary}</p>
        <p className="mt-6 text-[21px]">{card.author} <time dateTime={card.date}>{card.date}</time></p>
      </div>
      {photo && <img className="image-section shrink-0" src={photo} alt="新闻配图" />}
    </div>
  </article>;
}

function App() {
  const [card, setCard] = useState(templates[0]);
  const [template, setTemplate] = useState("0");
  const [photo, setPhoto] = useState("");
  const [message, setMessage] = useState("");
  const [exporting, setExporting] = useState(false);
  const [scale, setScale] = useState(1);
  const preview = useRef(null);
  const exportStage = useRef(null);
  const uploadVersion = useRef(0);

  useLayoutEffect(() => {
    const observer = new ResizeObserver(([size]) => setScale(size.contentRect.width / 1200));
    observer.observe(preview.current);
    return () => observer.disconnect();
  }, []);

  function acceptFile(file) {
    if (!file) return;
    const selected = ++uploadVersion.current;
    if (!["image/png", "image/jpeg", "image/webp"].includes(file.type) || file.size > 5 * 1024 * 1024) {
      setMessage("请选择 5 MB 以内的 PNG、JPEG 或 WebP 图片。");
      return;
    }
    const reader = new FileReader();
    reader.onerror = () => { if (selected === uploadVersion.current) setMessage("无法读取这张图片。"); };
    reader.onload = async () => {
      const image = new Image();
      image.src = reader.result;
      try {
        await image.decode();
        if (selected !== uploadVersion.current) return;
        setPhoto(reader.result);
        setMessage("已载入图片。");
      } catch {
        if (selected === uploadVersion.current) setMessage("图片内容无法解码。");
      }
    };
    reader.readAsDataURL(file);
  }

  async function exportPng() {
    setExporting(true);
    setMessage("正在生成 PNG…");
    try {
      await document.fonts.ready;
      const canvas = await html2canvas(exportStage.current.firstElementChild, { width: 1200, height: 630, scale: 1, logging: false });
      const file = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
      if (!file) throw new Error("PNG encoding failed");
      const url = URL.createObjectURL(file);
      const link = document.createElement("a");
      link.href = url;
      link.download = "city-brief.png";
      link.click();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
      setMessage("PNG 已生成。");
    } catch {
      setMessage("PNG 导出失败,请重试。");
    } finally {
      setExporting(false);
    }
  }

  return <main className="mx-auto max-w-7xl px-4 py-7">
    <h1 className="font-editorial text-3xl font-bold">城市简报卡片</h1>
    <div className="mt-6 grid gap-6 lg:grid-cols-[21rem_minmax(0,1fr)]">
      <section aria-label="编辑" className="grid gap-3 rounded border border-[#c7beaf] bg-paper p-5">
        <label>预设模板<select value={template} onChange={(ev) => {
          setTemplate(ev.target.value); setCard(templates[Number(ev.target.value)]);
        }}><option value="0">城市更新</option><option value="1">文化活动</option><option value="2">交通提醒</option></select></label>
        {fields.map(([key, label, max]) => {
          const props = { value: card[key], maxLength: max, onChange: (ev) => setCard({ ...card, [key]: ev.target.value }) };
          return <div key={key} className="grid gap-1"><label htmlFor={key}>{label}</label>{key === "summary" ? <textarea id={key} {...props} /> : <input id={key} {...props} type={key === "date" ? "date" : "text"} />}</div>;
        })}
        <div className="rounded border border-dashed border-accent p-3" data-testid="drop-area"
          onDragOver={(event) => event.preventDefault()}
          onDrop={(event) => { event.preventDefault(); acceptFile(event.dataTransfer.files[0]); }}>
          <label>选择或拖入配图<input type="file" accept="image/png,image/jpeg,image/webp"
            onChange={(event) => acceptFile(event.target.files[0])} /></label>
          {photo && <button type="button" className="mt-2 underline" onClick={() => {
            ++uploadVersion.current; setPhoto(""); setMessage("已移除配图。");
          }}>移除配图</button>}
        </div>
        <button type="button" className="rounded bg-ink px-4 py-2 text-white disabled:opacity-60"
          disabled={exporting} onClick={exportPng}>{exporting ? "正在导出…" : "下载 PNG"}</button>
        <p role="status" className="min-h-6">{message}</p>
      </section>
      <section aria-label="实时预览">
        <div ref={preview} className="preview-frame"><NewsCard card={card} photo={photo} style={{ transform: "scale(" + scale + ")" }} /></div>
      </section>
    </div>
    <div ref={exportStage} className="export-stage" aria-hidden="true"><NewsCard card={card} photo={photo} /></div>
  </main>;
}

createRoot(document.getElementById("root")).render(<App />);
预期结果 · 待实际运行核验
  • 切换三个模板、修改六个字段后预览同步。选择文件或拖放可解码配图,错误文件得到反馈。浏览器下载 1200×630 PNG,窄屏下纵向排列。
试用中文编辑、预设、配图与 PNG 导出

所需环境:React 18.3.1、Tailwind CSS 3.4.18、Vite 6.4.3、html2canvas 1.4.1、本机 Edge。

当前源码 SHA256:3ae606a7369589a0ec108df7119fa15449f7cbc5b23360f32180a7648a54df3c

运行独立项目

解压后用 npm ci 安装固定依赖,执行 npm run build,再用本机 HTTP 服务查看 dist/index.html。预先构建的 dist 也可直接由本机 HTTP 服务提供。

下载新闻卡片源码与本地构建结果

所需环境:React 18.3.1、Tailwind CSS 3.4.18、Vite 6.4.3、html2canvas 1.4.1、本机 Edge。

ZIP SHA256:1d6658727ee2bc372829613f495f465641cab33832a7163304cc10d3b4714caa

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么用固定尺寸的导出卡片?

展开参考解答

屏幕预览缩放和设备像素密度会变化。导出使用独立尺寸并明确 scale,才能校验最终文件。

规范与官方依据