diff --git a/__test__/index.spec.ts b/__test__/index.spec.ts index 654e4e3a..dd7c1d5a 100755 --- a/__test__/index.spec.ts +++ b/__test__/index.spec.ts @@ -270,6 +270,29 @@ test('should be load custom fontDirs(no defaultFontFamily option)', (t) => { t.is(originPixels.join(',').match(/0,0,255/g)?.length, 1726) }) +test('The defaultFontFamily is not found in the OS and needs to be fallback', (t) => { + const svg = ` + + + Abc + + + ` + const resvg = new Resvg(svg, { + font: { + loadSystemFonts: true, + defaultFontFamily: 'this-is-a-non-existent-font-family', + }, + }) + const pngData = resvg.render() + const originPixels = pngData.pixels.toJSON().data + // Find the number of blue `rgb(0,255,255)`pixels + const matchPixels = originPixels.join(',').match(/0,0,255/g) + console.info('✅ matchPixels length =', matchPixels?.length) + t.true(matchPixels !== null) // If the font is not matched, there are no blue pixels. + t.true((matchPixels?.length ?? 0) > 1500) +}) + test('Async rendering', async (t) => { const filePath = '../example/text.svg' const svg = await fs.readFile(join(__dirname, filePath)) diff --git a/src/fonts.rs b/src/fonts.rs index c5c50e31..5b6ddd4c 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -172,16 +172,16 @@ fn set_wasm_font_families( fontdb.set_monospace_family(&default_font_family); } +/// 查询指定 font family 的字体是否存在,如果不存在则使用 fallback_font_family 代替。 #[cfg(not(target_arch = "wasm32"))] fn find_and_debug_font_path(fontdb: &mut Database, font_family: &str) { - // 查找指定字体的路径 let query = Query { families: &[Family::Name(font_family)], ..Query::default() }; let now = std::time::Instant::now(); - // 当前使用的字体是否存在 + // 查询当前使用的字体是否存在 match fontdb.query(&query) { Some(id) => { let (src, index) = fontdb.face_source(id).unwrap(); @@ -195,6 +195,13 @@ fn find_and_debug_font_path(fontdb: &mut Database, font_family: &str) { } } None => { + let fallback_font_family = "Arial".to_string(); + fontdb.set_serif_family(&fallback_font_family); + fontdb.set_sans_serif_family(&fallback_font_family); + fontdb.set_cursive_family(&fallback_font_family); + fontdb.set_fantasy_family(&fallback_font_family); + fontdb.set_monospace_family(&fallback_font_family); + warn!( "Warning: The default font-family '{}' not found.", font_family