Skip to content

Commit

Permalink
fix: the quality of toDataURL should between 0 and 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Aug 6, 2022
1 parent 82ee1c5 commit 27e87df
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
4 changes: 2 additions & 2 deletions __test__/draw.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ test('JPEG toDataURL with quality', async (t) => {
const { ctx, canvas } = t.context
drawTranslate(ctx)

const output = canvas.toDataURL('image/jpeg', 20)
const output = canvas.toDataURL('image/jpeg', 0.2)
const prefix = 'data:image/jpeg;base64,'
t.true(output.startsWith(prefix))
const imageBase64 = output.substring(prefix.length)
Expand All @@ -958,7 +958,7 @@ test('WebP toDataURL with quality', async (t) => {
const { ctx, canvas } = t.context
drawTranslate(ctx)

const output = canvas.toDataURL('image/webp', 100)
const output = canvas.toDataURL('image/webp', 1)
const prefix = 'data:image/webp;base64,'
t.true(output.startsWith(prefix))
const imageBase64 = output.substring(prefix.length)
Expand Down
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,8 +335,10 @@ fn data(ctx: CallContext) -> Result<JsBuffer> {
fn to_data_url(ctx: CallContext) -> Result<JsString> {
let mime_js = ctx.get::<JsString>(0)?.into_utf8()?;
let mime = mime_js.as_str()?;
let quality = match ctx.get::<JsNumber>(1)?.get_uint32() {
Ok(number) => number as u8,
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
// quality is a number between 0.0 and 1.0
let quality = match ctx.get::<JsNumber>(1)?.get_double() {
Ok(number) => (number * 100.0) as u8,
Err(_e) => match mime {
MIME_WEBP => DEFAULT_WEBP_QUALITY,
_ => DEFAULT_JPEG_QUALITY, // https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
Expand Down

1 comment on commit 27e87df

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark

Benchmark suite Current: 27e87df Previous: 82ee1c5 Ratio
Draw house#skia-canvas 24 ops/sec (±0.49%) 26 ops/sec (±0.36%) 1.08
Draw house#node-canvas 26 ops/sec (±0.3%) 21 ops/sec (±0.28%) 0.81
Draw house#@napi-rs/skia 23 ops/sec (±0.12%) 23 ops/sec (±0.18%) 1
Draw gradient#skia-canvas 23 ops/sec (±0.05%) 25 ops/sec (±0.03%) 1.09
Draw gradient#node-canvas 25 ops/sec (±0.46%) 21 ops/sec (±0.19%) 0.84
Draw gradient#@napi-rs/skia 22 ops/sec (±0.19%) 22 ops/sec (±0.19%) 1

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.