使用npm发布一款简易图形验证码插件

本文介绍了如何编写一个简单的验证码插件,包括插件的构造函数、初始化、生成和刷新验证码、校验等功能。接着,讲解了如何注册npm账户并发布npm包,遵循的规范包括package.json、README.md和入口文件的创建。最后,展示了在Vue项目中如何引入并使用该验证码插件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、编写插件代码

代码很简单,没有特别复杂的逻辑,所以不过多赘述

export default class VerificationCode {
  constructor(options) {
    this.options = {
      id: "", //容器ID
      canvasId: "", // canvas的ID
      width: "80",
      height: "30",
      code: "",
    };

    if (Object.prototype.toString.call(options) === "[object Object]") {
      for (const i in options) {
        this.options[i] = options[i];
      }
    } else {
      this.options.id = options;
    }
    this._init();
  }
  // 初始化
  _init() {
    const canvas = document.getElementById(this.options.canvasId);

    canvas.id = this.options.canvasId;
    canvas.width = this.options.width;
    canvas.height = this.options.height;
    canvas.style.cursor = "pointer";
    canvas.innerHTML = "<span style='color: red'>你的浏览器不支持canvas</span>";
    canvas.onclick = () => {
      this.refreshCode();
    };
  }
  // 生成验证码
  refreshCode() {
    const canvas = document.getElementById(this.options.canvasId);
    let ctx = null,
      arr = "0,1,2,3,4,5,6,7,8,9".split(",").concat(this.letters()); // 数字和大小写字母的数组
    if (canvas.getContext) {
      ctx = canvas.getContext("2d");
    } else {
      return false;
    }
    ctx.textBaseline = "middle"; // 文字上下居中
    ctx.fillStyle = this.randomColor(180, 240); // 背景填充色随机
    ctx.fillRect(0, 0, this.options.width, this.options.height); // 填充背景

    for (let i = 0; i <= 4; i++) {
      let t = arr[this.randomNum(0, arr.length)]; // 随机字符
      this.options.code += t; // 生成五个随机字符
      ctx.font =
        this.randomNum(this.options.height / 2, this.options.height) +
        "px SimHei";
      ctx.fillStyle = this.randomColor(50, 160); // 字体颜色
      ctx.shadowOffsetX = this.randomNum(-3, 3); // 左右阴影偏移
      ctx.shadowOffsetY = this.randomNum(-3, 3); // 上下阴影偏移
      ctx.shadowBlur = this.randomNum(-3, 3); // 阴影模糊级别
      ctx.shadowColor = "rgba(0, 0, 0, 0.3)"; // 阴影颜色
      let x = (this.options.width / 5) * i;
      let y = this.options.height / 2;
      ctx.translate(x, y);
      ctx.fillText(t, 0, 0);
      ctx.translate(-x, -y);
    }
  }
  // 校验
  check(code) {
    return code.toLowerCase() === this.options.code.toLowerCase();
  }
  // 大小写字母
  letters() {
    let big = [],
      small = [];
    for (let i = 65; i < 91; i++) {
      big.push(String.fromCharCode(i));
    }
    for (let i = 97; i < 123; i++) {
      small.push(String.fromCharCode(i));
    }
    return small.concat(big);
  }
  // 随机数
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
  }
  // 随机颜色
  randomColor(min, max) {
    let r = this.randomNum(min, max),
      g = this.randomNum(min, max),
      b = this.randomNum(min, max);
    return "rgb(" + r + ", " + g + ", " + b + ")";
  }
}

二、注册npm账户

注册地址:点击跳转注册

  • 用户名 XXX
  • 邮箱 XXX@XX
  • 密码 **********

三、发布npm包

1、npm包规范官方建议至少包含:
  • package.json (包的基本信息)
  • README.md (说明文档)
  • index.js (入口文件)
2、以下是我的package.json文件,可以使用npm init初始化,也可以手动添加。
{
  "name": "@kayrain/code",
  "version": "1.0.1",
  "description": "picture verification code.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "code"
  ],
  "author": "kayrain",
  "license": "ISC"
}

3、README.md文件:
This is my first npm package.
4、公共发布

(1)添加npm用户,依次输入用户名、密码、邮箱

npm adduser

(2)公共发布

npm publish --access public

(3)出现以下信息就说明发布成功了
在这里插入图片描述
(4)在npm中搜索包
在这里插入图片描述

5、在vue中使用插件
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" /> 
    <div id="container">
      <canvas id="canvas"></canvas>
      <input class="code" type="text" id="input" />
      <input @click="handleVerify" type="button" value="Enter" id="btn" />
    </div>
  </div>
</template>

<script>
import Verify from "@kayrain/code";

export default {
  name: "App",
  data() {
    return {
      verify: null,
    };
  },
  methods: {
    handleVerify() {
      const res = this.verify.check(document.getElementById("input").value);
      if (res) {
        alert("RIGHT");
      } else {
        alert("FALSE");
      }
    },
  },
  mounted() {
    this.verify = new Verify({
      id: "container", // containerID
      canvasId: "canvas", // canvasID
      width: "80",
      height: "30",
      code: "",
    });

    this.verify.refreshCode();
  },
};
</script> 

图示:
在这里插入图片描述
以上就是npm包发布基本流程。

GitHub地址:@kayrain/code
参考:npm发布包教程(二):发布包

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值