Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Uncaught TypeError: Failed to execute 'createRadialGradient' on … #898

Merged
merged 8 commits into from
Apr 15, 2022
18 changes: 14 additions & 4 deletions src/canvas/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { GradientObject } from '../graphic/Gradient';
import { RectLike } from '../core/BoundingRect';
import Path from '../graphic/Path';

export function isSafeNum(num: number, nonNegative = false) {
// NaN、Infinity、undefined、'xx',non-negative
return !(!isFinite(num) || nonNegative && num < 0);
}

export function createLinearGradient(
this: void,
ctx: CanvasRenderingContext2D,
Expand All @@ -23,10 +28,10 @@ export function createLinearGradient(
}

// Fix NaN when rect is Infinity
x = isNaN(x) ? 0 : x;
x2 = isNaN(x2) ? 1 : x2;
y = isNaN(y) ? 0 : y;
y2 = isNaN(y2) ? 0 : y2;
x = isSafeNum(x) ? x : 0;
x2 = isSafeNum(x2) ? x2 : 1;
y = isSafeNum(y) ? y : 0;
y2 = isSafeNum(y2) ? y2 : 0;

const canvasGradient = ctx.createLinearGradient(x, y, x2, y2);

Expand All @@ -46,12 +51,17 @@ export function createRadialGradient(
let x = obj.x == null ? 0.5 : obj.x;
let y = obj.y == null ? 0.5 : obj.y;
let r = obj.r == null ? 0.5 : obj.r;

if (!obj.global) {
x = x * width + rect.x;
y = y * height + rect.y;
r = r * min;
}

x = isSafeNum(x) ? x : 0.5;
y = isSafeNum(y) ? y : 0.5;
r = isSafeNum(r, true) ? r : 0.5;
Copy link
Contributor

Choose a reason for hiding this comment

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

Seems only one number needs to be check positive. In this case I will prefer keeping the isSafeNum simpler and more cohesion that only accept one parameter number. Monomorphic function is always better than polymorphic function, on both code style and performance.

So the r check can be

r = isSafeNum(r) && r >= 0 ? r : 0.5


const canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);

return canvasGradient;
Expand Down
2 changes: 1 addition & 1 deletion test/ut/spec/contain/Sector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe('Path', function () {
cy: 625.5,
startAngle: -1.5707963267948966,
endAngle: 4.71238898038469,
innerCornerRadius: 5,
Copy link
Contributor

Choose a reason for hiding this comment

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

This change seems to be unnecessary?

// innerCornerRadius: 5,
r: 218.92499999999998,
r0: 93.825
},
Expand Down