mirror of
https://github.com/konvajs/konva.git
synced 2025-11-24 16:53:06 +08:00
Update hit detection system to handle canvas farbling.
This commit is contained in:
@@ -3,6 +3,10 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## 10.0.9 (2025-11-20)
|
||||
|
||||
- Update hit detection system to handle canvas farbling. Hit detection should work better on Brave browser.
|
||||
|
||||
## 10.0.8 (2025-10-24)
|
||||
|
||||
- Fixed opacity level when a cached shape has opacity, fill and stroke
|
||||
|
||||
@@ -182,42 +182,6 @@ export class SceneCanvas extends Canvas {
|
||||
}
|
||||
}
|
||||
|
||||
// function checks if canvas farbling is active
|
||||
// canvas farbling is a Browser security feature, it break konva internals
|
||||
function isCanvasFarblingActive() {
|
||||
const c = Util.createCanvasElement();
|
||||
c.width = 1;
|
||||
c.height = 1;
|
||||
const ctx = c.getContext('2d', {
|
||||
willReadFrequently: true,
|
||||
}) as CanvasRenderingContext2D;
|
||||
ctx.clearRect(0, 0, 1, 1);
|
||||
ctx.fillStyle = 'rgba(255,0,255,1)'; // clear #FF00FF, no alpha
|
||||
ctx.fillRect(0, 0, 1, 1);
|
||||
const d = ctx.getImageData(0, 0, 1, 1).data;
|
||||
const exact = d[0] === 255 && d[1] === 0 && d[2] === 255 && d[3] === 255;
|
||||
return !exact;
|
||||
}
|
||||
|
||||
function isBraveBrowser() {
|
||||
if (typeof navigator === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
// @ts-ignore
|
||||
return navigator.brave?.isBrave() ?? false;
|
||||
}
|
||||
|
||||
let warned = false;
|
||||
function checkHitCanvasSupport() {
|
||||
if (isBraveBrowser() && isCanvasFarblingActive() && !warned) {
|
||||
warned = true;
|
||||
Util.error(
|
||||
'Looks like you have "Brave shield" enabled in your browser. It breaks KonvaJS internals. Please disable it. You may need to ask your users to do the same.'
|
||||
);
|
||||
}
|
||||
return isBraveBrowser() && isCanvasFarblingActive();
|
||||
}
|
||||
|
||||
export class HitCanvas extends Canvas {
|
||||
hitCanvas = true;
|
||||
constructor(config: ICanvasConfig = { width: 0, height: 0 }) {
|
||||
@@ -225,6 +189,5 @@ export class HitCanvas extends Canvas {
|
||||
|
||||
this.context = new HitContext(this);
|
||||
this.setSize(config.width, config.height);
|
||||
checkHitCanvasSupport();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,9 +367,10 @@ export class Layer extends Container<Group | Shape> {
|
||||
const p3 = p[3];
|
||||
|
||||
// fully opaque pixel
|
||||
|
||||
if (p3 === 255) {
|
||||
const colorKey = Util._rgbToHex(p[0], p[1], p[2]);
|
||||
const shape = shapes[HASH + colorKey];
|
||||
const colorKey = Util.getHitColorKey(p[0], p[1], p[2]);
|
||||
const shape = shapes[colorKey];
|
||||
if (shape) {
|
||||
return {
|
||||
shape: shape,
|
||||
|
||||
11
src/Shape.ts
11
src/Shape.ts
@@ -203,12 +203,21 @@ export class Shape<
|
||||
super(config);
|
||||
// set colorKey
|
||||
let key: string;
|
||||
let attempts = 0;
|
||||
|
||||
while (true) {
|
||||
key = Util.getRandomColor();
|
||||
key = Util.getHitColor();
|
||||
if (key && !(key in shapes)) {
|
||||
break;
|
||||
}
|
||||
attempts++;
|
||||
if (attempts >= 10000) {
|
||||
Util.warn(
|
||||
'Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it.'
|
||||
);
|
||||
key = Util.getRandomColor();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.colorKey = key;
|
||||
|
||||
83
src/Util.ts
83
src/Util.ts
@@ -446,6 +446,9 @@ const OBJECT_ARRAY = '[object Array]',
|
||||
RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
|
||||
let animQueue: Array<Function> = [];
|
||||
|
||||
// Cache for canvas farbling detection
|
||||
let _isCanvasFarblingActive: boolean | null = null;
|
||||
|
||||
const req =
|
||||
(typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) ||
|
||||
function (f) {
|
||||
@@ -583,6 +586,84 @@ export const Util = {
|
||||
}
|
||||
return HASH + randColor;
|
||||
},
|
||||
/**
|
||||
* Check if canvas farbling is active (e.g., Brave browser fingerprinting protection)
|
||||
* @method
|
||||
* @memberof Konva.Util
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
isCanvasFarblingActive() {
|
||||
if (_isCanvasFarblingActive !== null) {
|
||||
return _isCanvasFarblingActive;
|
||||
}
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
_isCanvasFarblingActive = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
const c = this.createCanvasElement();
|
||||
c.width = 1;
|
||||
c.height = 1;
|
||||
const ctx = c.getContext('2d', {
|
||||
willReadFrequently: true,
|
||||
}) as CanvasRenderingContext2D;
|
||||
ctx.clearRect(0, 0, 1, 1);
|
||||
ctx.fillStyle = 'rgba(255,0,255,1)'; // clear #FF00FF, no alpha
|
||||
ctx.fillRect(0, 0, 1, 1);
|
||||
const d = ctx.getImageData(0, 0, 1, 1).data;
|
||||
const exact = d[0] === 255 && d[1] === 0 && d[2] === 255 && d[3] === 255;
|
||||
_isCanvasFarblingActive = !exact;
|
||||
this.releaseCanvas(c);
|
||||
return _isCanvasFarblingActive;
|
||||
},
|
||||
/**
|
||||
* Get a random color for hit detection (normalized if farbling is active)
|
||||
* @method
|
||||
* @memberof Konva.Util
|
||||
* @returns {String} hex color string
|
||||
*/
|
||||
getHitColor(): string {
|
||||
const color = this.getRandomColor();
|
||||
return this.isCanvasFarblingActive()
|
||||
? this.getSnappedHexColor(color)
|
||||
: color;
|
||||
},
|
||||
/**
|
||||
* Get hit color key from RGB values (normalized if farbling is active)
|
||||
* @method
|
||||
* @memberof Konva.Util
|
||||
* @param {Number} r - red component (0-255)
|
||||
* @param {Number} g - green component (0-255)
|
||||
* @param {Number} b - blue component (0-255)
|
||||
* @returns {String} hex color key string
|
||||
*/
|
||||
getHitColorKey(r: number, g: number, b: number): string {
|
||||
if (this.isCanvasFarblingActive()) {
|
||||
r = Math.round(r / 5) * 5;
|
||||
g = Math.round(g / 5) * 5;
|
||||
b = Math.round(b / 5) * 5;
|
||||
}
|
||||
return HASH + this._rgbToHex(r, g, b);
|
||||
},
|
||||
/**
|
||||
* Snap hex color values to end with 0 (normalize for canvas farbling)
|
||||
* @method
|
||||
* @memberof Konva.Util
|
||||
* @param {String} hex - hex color string (e.g., "#ff00ff")
|
||||
* @returns {String} normalized hex color string
|
||||
*/
|
||||
getSnappedHexColor(hex: string): string {
|
||||
const rgb = this._hexToRgb(hex);
|
||||
return (
|
||||
HASH +
|
||||
this._rgbToHex(
|
||||
Math.round(rgb.r / 5) * 5,
|
||||
Math.round(rgb.g / 5) * 5,
|
||||
Math.round(rgb.b / 5) * 5
|
||||
)
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* get RGB components of a color
|
||||
@@ -1122,4 +1203,4 @@ export const Util = {
|
||||
},
|
||||
};
|
||||
|
||||
export type AnyString<T> = T | (string & {})
|
||||
export type AnyString<T> = T | (string & {});
|
||||
|
||||
@@ -31,14 +31,62 @@
|
||||
const layer = new Konva.Layer();
|
||||
stage.add(layer);
|
||||
|
||||
const circle = new Konva.Circle({
|
||||
x: stage.width() / 2,
|
||||
y: stage.height() / 2,
|
||||
radius: 100,
|
||||
fill: 'red',
|
||||
draggable: true,
|
||||
// Given gridRows and gridCols, compute maximum possible radius and position circles
|
||||
const gridRows = 200;
|
||||
const gridCols = 200;
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
|
||||
// Calculate spacing and radius so circles fit entire window
|
||||
// There are (gridCols - 1) spaces between centers horizontally, and (gridRows - 1) vertically
|
||||
// The available width is "width", so (gridCols) circles and (gridCols-1) spaces between
|
||||
// The diameter must fit: gridCols * diameter + (gridCols - 1) * gap <= width
|
||||
// But to maximize, gap should equal to at least 0, so best layout is circles tangent
|
||||
|
||||
// So the max diameter horizontally is width / gridCols
|
||||
// Likewise for vertical
|
||||
const cellWidth = width / gridCols;
|
||||
const cellHeight = height / gridRows;
|
||||
const radius = Math.min(cellWidth, cellHeight) / 2;
|
||||
|
||||
const circles = [];
|
||||
|
||||
// Create grid of circles - centers in each cell's center
|
||||
for (let row = 0; row < gridRows; row++) {
|
||||
for (let col = 0; col < gridCols; col++) {
|
||||
const cx = cellWidth * col + cellWidth / 2;
|
||||
const cy = cellHeight * row + cellHeight / 2;
|
||||
const c = new Konva.Circle({
|
||||
x: cx,
|
||||
y: cy,
|
||||
radius: radius,
|
||||
fill: Konva.Util.getRandomColor(),
|
||||
id: `circle-${row}-${col}`,
|
||||
});
|
||||
layer.add(circle);
|
||||
circles.push({
|
||||
node: c,
|
||||
x: cx,
|
||||
y: cy,
|
||||
row,
|
||||
col,
|
||||
});
|
||||
layer.add(c);
|
||||
}
|
||||
}
|
||||
layer.draw();
|
||||
|
||||
// Test hits at each center
|
||||
for (const cInfo of circles) {
|
||||
const { node, x, y } = cInfo;
|
||||
const hit = stage.getIntersection({ x, y });
|
||||
if (hit !== node) {
|
||||
const gotId = hit ? hit.id && hit.id() : null;
|
||||
console.error(
|
||||
`Hit test failed at (${x},${y}): expected id=${node.id()}, got id=${gotId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log('Hit test grid check complete.');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user