You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Konva.js中onClick与onContentClick有何区别?Stage事件相关疑问

Difference Between onClick and onContentClick in Konva.js

Awesome question—this is a common point of confusion with Konva.js, especially since the docs don’t spell out the difference super explicitly. Let me break down exactly how these two events differ, and confirm that contentClick is absolutely not just an alias—it has a specific, distinct purpose.

1. The General click Event (onClick)

  • This is Konva’s standard click event, tied to the entire container of the node (whether that’s a Stage, Layer, or Shape).
  • For a Stage, this means it triggers if you click anywhere inside the Stage’s outer wrapper div—including the padding area around the actual canvas content (if you’ve set a padding property on your Stage).
  • It follows Konva’s normal event bubbling rules: if you click a child node (like a shape inside the Stage), the click event will bubble up to the Stage unless you explicitly stop propagation with event.cancelBubble = true.

2. The Targeted contentClick Event (onContentClick)

  • This event is strictly bound to the actual visual content area of the node. For a Stage, that’s the underlying canvas element (the region defined by your Stage’s width and height properties).
  • It will not trigger if you click the padding area around the Stage’s canvas—only clicks on the canvas itself count.
  • For other nodes (like shapes or layers), it targets the visible, rendered content of the node (e.g., the filled area of a rectangle, not any empty space around it that’s part of the node’s container).
  • Unlike the general click event, it doesn’t bubble up from child nodes—so clicking a shape inside the Stage won’t trigger the Stage’s contentClick event (only direct clicks on the Stage’s canvas content do).

Quick Example to Illustrate

If you set up a Stage like this:

const stage = new Konva.Stage({
  container: 'container',
  width: 500,
  height: 300,
  padding: 50 // Adds 50px of empty space around the canvas
});
  • Clicking the 50px padding area around the canvas will fire the Stage’s click event, but not contentClick.
  • Clicking the 500x300 canvas area (either empty space or a shape on it) will fire both events (unless you stop propagation for click).

So in short: click covers the entire node container, while contentClick is limited to the node’s actual rendered content. They serve different use cases—use contentClick when you only care about interactions with the visible canvas, and click if you want to capture all clicks within the node’s wrapper.

内容的提问来源于stack exchange,提问作者navono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:37:23