首页 > 解决方案 > 在 TypeScript 中生成颜色、高度和 base64 字符串

问题描述

我试图找出是否可以生成具有以下 3 个值的 base64 代码:color, width, height. (没有外部巨头npm lib)我只遇到过一个名为base64-js的lib。但是,我不需要大多数功能。

编辑:感谢维克多。我稍微编辑了他的代码,结果是:

convertToDataURLViaCanvas(outputFormat, width, height, color) {
    return new Promise((resolve) => {
        let canvas = <HTMLCanvasElement>document.createElement('CANVAS');
        canvas.height = height;
        canvas.width = width;
        const ctx = canvas.getContext('2d');

        // fill the entire canvas with color
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        let dataURL = canvas.toDataURL(outputFormat);
        // callback(dataURL);
        canvas = null;
        resolve(dataURL);
    });
}

奇迹般有效。谢谢你!

标签: typescriptbase64

解决方案


正如@HB 所说,div对于这样的占位符, a 应该足够了。但是,如果您需要 Base64 编码的图像,您可以使用以下方法获取它canvas.toDataURL()

function insertPlaceholder(color, width, height) {
    const canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image();

    canvas.width = width;
    canvas.height = height;

    ctx.fillStyle = color;
    ctx.fillRect(0, 0, width, height);

    img.src = canvas.toDataURL(); //-> data:image/png;base64,iVBORw0K...
    document.body.appendChild(img);
}

用法:

insertPlaceholder('red', 250, 250);

推荐阅读