点击查看html编辑器说明文档

使用 canvas 绘制渐变颜色的文字edit icon

|
|
Fork(复制)
|
|
作者:
lynn-ssk

👉 新版编辑器已上线,点击进行体验吧!

BUG反馈
嵌入
设置
下载
HTML
格式化
支持Emmet,输入 p 后按 Tab键试试吧!
<head> ...
展开
</head>
<body>
            
            <canvas id="canvas" width="300" height="180"></canvas>
        
</body>
CSS
格式化
            
            
        
JS
格式化
            
            // 创建画布
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// 文本基线设置为 "top",方便文字定位时使用文字左上角进行定位,
// 且之后使用的获取文字占用高度的属性 actualBoundingBoxDescent
// 也需要此设置才能正确获取。
ctx.textBaseline = "top"
ctx.font = "bold 40px 'Fira Sans'"; //定义文字样式

// 提取文字占用宽高,渐变的范围就是通过文字的宽高来定义的
let textMetrics = ctx.measureText("阳光知道文字");
let text_width = textMetrics.width;
let text_height = textMetrics.actualBoundingBoxDescent;

// 定义渐变过度颜色
let colors = [
    "rgb(255, 149, 0)",//橙色
    "rgb(237, 176, 0)",
    "rgb(204, 204, 0)",
    "rgb(153, 230, 0)",
    "rgb(4, 255, 0)",  //绿色
];

/**
 * 获取一个线性渐变颜色
 * 参数 x0, y0, x1, y1 为 createLinearGradient 使用的参数
 * 参数 textX,textY 为文字绘制的位置
 */
function getLingrad(x0, y0, x1, y1,textX,textY){
    // 需要根据文字绘制的位置 (textX,textY) 偏移
    let gradient = ctx.createLinearGradient(
        x0+textX,
        y0+textY,
        x1+textX,
        y1+textY
    );
    colors.map((item,i) =>{
        //偏移值根据颜色个数平均分。
        gradient.addColorStop(i/(colors.length-1), item);
    })
    return gradient;
}

/**
 * 获取一个径向渐变颜色
 * 参数 x0, y0, r0, x1, y1, r1 为 createRadialGradient 使用的参数
 * 参数 textX,textY 为文字绘制的位置
 */
function getRadiald(x0, y0, r0, x1, y1, r1,textX,textY){
    let gradient = ctx.createRadialGradient(
        x0 + textX,
        y0 + textY,
        r0,
        x1 + textX,
        y1 + textY,
        r1);
    colors.map((item,i) =>{
        //偏移值根据颜色个数平均分。
        gradient.addColorStop(i/(colors.length-1), item);
    });
    return gradient;
}

// 绘制文字,从左到右渐变
let textP = { x:0, y:0 };// 文字绘制的位置
ctx.fillStyle = getLingrad(0, 0, text_width, 0, textP.x, textP.y);
ctx.fillText("阳光知道文字", textP.x, textP.y);

// 绘制文字,从上到下渐变
textP = { x:0, y:text_height }
ctx.fillStyle = getLingrad(0, 0, 0, text_height,textP.x, textP.y);
ctx.fillText("阳光知道文字", textP.x, textP.y);

// 绘制文字,由外向内渐变
textP = { x:0, y:text_height * 2 }
ctx.fillStyle = getRadiald(
    text_width/2, text_height/2, 100,
    text_width/2, text_height/2, 0,
    textP.x, textP.y);// 径向渐变由中心开始渐变,宽高各取一半就是圆心
ctx.fillText("阳光知道文字", textP.x, textP.y);

// 绘制文字,由内向外渐变
textP = { x:0, y:text_height * 3 }
ctx.fillStyle = getRadiald(
    text_width/2, text_height/2, 0,
    text_width/2, text_height/2, 100,
    textP.x, textP.y);// 径向渐变由中心开始渐变,宽高各取一半就是圆心
ctx.fillText("阳光知道文字", textP.x, textP.y);
        
预览
控制台