canvas元素是否有“变化”事件?
有没有办法将事件处理程序附加到 canvas
元素的 change 上?每当有东西在上面绘制任何东西时,我就需要触发一个函数。
Is there a way to attach event handler to a change of a canvas
element? I need to fire a function whenever something draws anything on it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,canvas 元素不提供任何事件,它只是一个普通的位图。
如果您确实想这样做,请劫持事件中内置的
上下文
上的所有调用,然后调用原始函数(您之前已复制)。我的建议:
不要这样做,会很慢并且难以维护。相反,您可以更改应用程序的设计,例如,您可以创建自定义绘图函数,该函数将抽象画布并将事件内容放入其中。
在进行大量绘图时,这还会带来额外的好处,即减少
context.*
调用(因此代码更干净)。No, the
canvas
element does not provide any events, it's just a plain bitmap.If you really want to do this, hijack all the calls on a
context
built in your events and then call the original function (which you have copied previously).My advice:
Do not do the above, it will be slow and hard to maintain. Instead change the design of your application, you could, for one, make custom drawing functions which will abstract the canvas and put in the event stuff there.
This would also have the added benefit of less
context.*
calls (therefore cleaner code) when doing a lot of drawing.您可以使用 mouseup 事件。
上面的 mouseup 文档实际上有一个很好的画布示例
You could use the mouseup event.
The mouseup docs above actually have a good canvas example
如果需要跟踪这些命令,我实际上会包装画布。这是一个仅跟踪几种方法的简单示例:
I would actually wrap the canvas iff needed to track these commands. Here's a simple example tracking only for a few methods:
对我来说,我在画布上附加了一个单击事件,并且我能够检测该画布上是否绘制了任何内容。
在这里小提琴 - http://jsfiddle.net/ashwyn/egXhT/2/
检查文本
//Event if Drawn
你就会明白在哪里。For me I attached a click event on the canvas and I am able to detect if any thing is drawn on that canvas.
Fiddle here - http://jsfiddle.net/ashwyn/egXhT/2/
Check for text
//Event if Drawn
and you will understand where.不存在事件处理程序,所以这就是我所做的:
我的图像操作程序(不是绘画包)使用两个画布;
一个用于操作,另一个用于撤消功能...
因此,在需要时可以轻松比较它们以进行更改。
要查询它们是否相同:
或返回相反的状态...找出它们是否已更改:
我希望这有帮助。
No event handler exists so here's what I do:
My image manipulating program (not a paint package) uses two canvases;
One for manipulation and the other for the undo function...
So it's easy to compare them for change whenever needed.
To query if they're the same:
Or return the reverse state... find out if they've changed:
I hope this helps.