Skip to content

Commit

Permalink
fix: allow svg canvas size modification (#928)
Browse files Browse the repository at this point in the history
* fix(SvgCanvas): allow canvas size modification

* test: add tests
  • Loading branch information
twlite authored Nov 6, 2024
1 parent 6724697 commit 15c7eab
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
9 changes: 9 additions & 0 deletions __test__/svg-canvas.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ test.beforeEach((t) => {
t.context.canvas = createCanvas(1024, 768, SvgExportFlag.ConvertTextToPaths)
})

test('should be able to adjust size', (t) => {
const { canvas } = t.context
canvas.width = 512
canvas.height = 384

t.is(canvas.width, 512)
t.is(canvas.height, 384)
})

test('should be able to export path/arc/rect', (t) => {
const { canvas } = t.context
const ctx = canvas.getContext('2d')
Expand Down
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,42 @@ impl<'scope> SVGCanvas<'scope> {
})
}
}

#[napi(setter)]
pub fn set_width(&mut self, env: Env, width: i32) -> Result<()> {
let width = (if width <= 0 { 350 } else { width }) as u32;
self.width = width;
let height = self.height;
let old_ctx = mem::replace(
&mut self.ctx.context,
Context::new(width, height, ColorSpace::default())?,
);
env.adjust_external_memory((width as i64 - old_ctx.width as i64) * 4)?;
Ok(())
}

#[napi(getter)]
pub fn get_width(&self) -> u32 {
self.width
}

#[napi(setter)]
pub fn set_height(&mut self, env: Env, height: i32) -> Result<()> {
let height = (if height <= 0 { 150 } else { height }) as u32;
self.height = height;
let width = self.width;
let old_ctx = mem::replace(
&mut self.ctx.context,
Context::new(width, height, ColorSpace::default())?,
);
env.adjust_external_memory((height as i64 - old_ctx.height as i64) * 4)?;
Ok(())
}

#[napi(getter)]
pub fn get_height(&self) -> u32 {
self.height
}
}

#[napi]
Expand Down
2 changes: 1 addition & 1 deletion src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ impl Path {
#[napi(js_name = "toSVGString")]
pub fn to_svg_string(&self, env: Env) -> Result<JsString> {
let sk_string = self.inner.to_svg_string();
unsafe { env.create_string_from_c_char(sk_string.ptr, sk_string.length) }
unsafe { env.create_string_from_c_char(sk_string.ptr, sk_string.length as isize) }
}

#[napi]
Expand Down

0 comments on commit 15c7eab

Please sign in to comment.