Skip to content

Latest commit

 

History

History
180 lines (134 loc) · 3.98 KB

项目构建.md

File metadata and controls

180 lines (134 loc) · 3.98 KB

从零构建koa项目Demo

初始化

  1. 首先创建koaDemo文件夹,并进入koaDemo

  2. npm init -y 生成package.json配置文件

  3. npm install koa -S

    ​ 注意:

    npm install xxx -S (--save)自动把包添加到dependencies

    npm install xxx -D (--save-dev)自动把包添加到devdependencies(开发环境)

  4. 创建js文件

       const Koa = require('koa');
    
       const app = new Koa();
    
       app.use(ctx => {
       ctx.body = 'Hello Koa';
       });
    
       app.listen(3000);

    注意:这里使用require导入Koa,如果使用import,直接node运行会报错,还需要安装配置babel

  5. 运行js文件

    node .\src\hello.js

  6. 这时浏览器访问 127.0.0.1:3000 就通了


安装babel的步骤:

为了使用es6的语法,我们安装babel,执行命令:

npm install -D babel-cli babel-preset-env

创建.babelrc文件

{
   "presets": ["babel-preset-env"]
}

执行命令,运行程序

.\node_modules\.bin\babel-node .\src\hello.js

(不过就目前的情况来看,不装babel,import语法是用不了的,async貌似是可以)


安装nodemon,使开发更便捷

npm i nodemon -D

然后在package.json中添加dev命令,这样每次src有改变,nodemon会自动帮我们重启项目

"scripts": {
   "dev": "nodemon --watch src --exec babel-node src/index.js"
  },

安装 koa/router,创建一个欢迎首页

npm i @koa/router -S

注意路由的注册方式

app.use(indexRouter.routes())
  .use(indexRouter.allowedMethods());

安装 koa-bodyparser

npm install koa-bodyparser -S

安装了koa-bodyparser后,可以直接用 ctx.request.body 访问请求体



实现功能

首先创建一个错误处理中间件,放在中间件的最上方,以便捕获到所有错误,返回状态码500

一、合成图片

支持 post 请求,需要传 canvas 参数,参数的接口如下表。

请求参数示例

canvas: {
  width: 375, // canvas 宽度
  height: 812, // canvas 高度
  temporarily: false, // 是否把图片上传到 cdn 。开发的时候使用。
  resources: [
    {
      type: 'image',  // 图片类型
      attributes: {
        url: 'src/resources/images/gamePaper/bg.png',
        style: {
          left: 0,
          top: 0,
          width: 375,
          height: 812,
        },
      },
    },
    {
      type: 'image',
      attributes: {
        url: 'http://tbfile.ixiaochuan.cn/img/png/id/670379726',
        style: {
          left: 65,
          top: 448,
          width: 246,
          height: 125,
        },
      },
    },
    {
      type: 'text',  // 文字类型
      attributes: {
        content: '考号:01029378748',
        style: {
          left: 46,
          top: 120,
          fontSize: 14,
          color: '#242529',
          fontSize:30,
          fontFamily: 'Impact'
        },
      },
    },
  ],
}

图片类型的 url 支持两种:

import xxxImg from 'file!../../images/xxx.png'
  • 本项目本地图片文件,读取本地图片比远程图片更快。建议按照项目名放在 src/resources 目录下。例如,src/resources/images/gamePaper/bg.png

返回值说明

接口名 method 返回值
/mergeimage post - temporarily 为 true , 临时(2分钟有效期)的图片 url 。否则,返回标识图片属性的结构(id / type 等)以及 合成的图片实体

二、查看合成图片/viewimage/:imageId

查看临时图片,imageId 由调用 /mergeimage 接口生成

三、预测文字的长度/measuretext

传参: { canvas: { fontSize: 17, fontFamily: 'serif', text: '你觉得我有多长', }, }

返回: {"ret":1,"data":{"width":119}}