Vue2 项目使用 CRC32 和 Unicode 编码生成字符串对应的颜色值

简介: 这篇文章介绍了在Vue 2项目中使用CRC32算法和Unicode编码来生成字符串对应的颜色值的两种方法,包括如何导入依赖、编写工具函数、在Vue原型上挂载以及具体的使用示例。

前言

简单记录一下在 Vue2 项目使用 CRC32 和 Unicode 编码生成字符串对应的颜色值。

一、使用 CRC32 转换字符串来生成十六进制颜色值

1.导入依赖

npm install crc-32

2.示例代码

(1)/src/utils/colorUtil.js

import Vue from 'vue'
import CRC32 from 'crc-32'

const stringToColor = (str) => {
   
    if (str) {
   
        str = Math.abs(CRC32.str(str)).toString(10);
        return '#' + str.substring(0, 6);
    } else {
   
        return 'transparent'; // 透明
    }
}

Vue.prototype.$stringToColor= stringToColor

3.全局引入

import './utils/colorUtil'

4.使用方式

示例一

const color = this.$stringToColor("这是一段字符串");
console.log(color);


示例二
<p>{
   {
    $stringToColor('HelloWorld') }}</p>

二、使用字符串 Unicode 编码生成 RGB 颜色值

1.示例代码

(1)/src/utils/colorUtil.js

import Vue from 'vue'

const stringToColor = (str) => {
   
    let hash = 0;
    for (var i = 0; i < str.length; i++) {
   
        hash = hash * 31 + str.charCodeAt(i);
        hash = intValue(hash);
    }
    let r = (hash & 0xFF0000) >> 16;
    let g = (hash & 0x00FF00) >> 8;
    let b = (hash & 0x0000FF);
    return 'rgba(' + r + ',' + g + ',' + b + ',' + '0.2)';
}

function intValue(num) {
   
    var MAX_VALUE = 0x7fffffff;
    var MIN_VALUE = -0x80000000;
    if(num > MAX_VALUE || num < MIN_VALUE)
    {
   
        return num &= 0xFFFFFFFF;
    }
    return num;
}

Vue.prototype.$stringToColor = stringToColor

2.全局引入

import './utils/colorUtil'

3.使用方式

示例一

const color = this.$stringToColor("这是一段字符串");
console.log(color);


示例二
<p>{
   {
    $stringToColor('HelloWorld') }}</p>
目录
相关文章
|
9月前
|
JavaScript
开发中的编码和解码(js的问题)
开发中的编码和解码(js的问题)
47 0
|
6月前
|
JavaScript 前端开发
JS二进制转10进制、十六进制
JS二进制转10进制、十六进制 【8月更文挑战第9天】
204 6
|
JSON JavaScript 数据格式
Vue中base64编码和解码
Vue中base64编码和解码
364 0
|
9月前
|
JavaScript 前端开发 数据安全/隐私保护
JavaScript学习 -- Hex编码
JavaScript学习 -- Hex编码
264 0
|
JavaScript
js中将byte数组转换成base64图片显示
js中将byte数组转换成base64图片显示
|
JavaScript C#
js base64编码,C#解码
js base64编码,C#解码
102 0
|
JavaScript 前端开发 Python
Python 技术篇 - 使用unicode_escape对js的escape()方法编码后的字符串进行解码实例演示
Python 技术篇 - 使用unicode_escape对js的escape()方法编码后的字符串进行解码实例演示
257 0
Python 技术篇 - 使用unicode_escape对js的escape()方法编码后的字符串进行解码实例演示
|
JavaScript
js之RGB->转换为十六进制
js之RGB->转换为十六进制
4994 0
|
JavaScript