typescript - 在 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);
});
}
奇迹般有效。谢谢你!
解决方案
正如@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);
推荐阅读
- swift - NSArrayController addObject 抛出异常
- java - 为什么打印 int 静态值会给出对象符号值,而不是实际值
- perl - Perl 命令行参数
- java - JavaFx KeyEvent on Rectangle doesn't work
- ios - 如何在 SwiftUI 的 ScrollView 中制作动画?SwiftUI 中的手风琴风格动画
- javascript - 如何修复“一个关闭按钮关闭所有模态”
- typescript - 为所有其他下拉菜单禁用一个下拉菜单的选定选项
- xamarin.android - 如何摆脱 Xamarin Android 上的这个资源 id 错误?
- javascript - 无服务器无法导入模块“处理程序”错误
- arduino - arduino 系统范围配置文件上的 Ardupilot 编译错误是“ArduPilot-Arduino-1.0.3-windows\hardware/tools/avr/etc/avrdude.conf”