javascript 画布元素是否有“更改”事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4648465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does canvas element have "change" event?
提问by Michal Till
Is there a way to attach event handler to a changeof a canvaselement? I need to fire a function whenever something draws anything on it.
有没有一种方法,以事件处理程序附加到改变一个的canvas元素吗?每当有东西在上面绘制任何东西时,我都需要触发一个函数。
回答by Ivo Wetzel
No, the canvaselement does not provide any events, it's just a plain bitmap.
不,该canvas元素不提供任何事件,它只是一个普通的位图。
If you really want to do this, hiHyman all the calls on a contextbuilt in your events and then call the original function (which you have copied previously).
如果您真的想这样做,请劫持对context内置事件的所有调用,然后调用原始函数(您之前已复制)。
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.
context.*在进行大量绘图时,这还具有更少调用(因此更干净的代码)的额外好处。
回答by Subtletree
You could use the mouseupevent.
您可以使用mouseup事件。
canvasElement.addEventListener('mouseup', e => {
// Fire function!
});
// or jQuery
$('canvas').on('mouseup', function() {
// Fire function!
});
The mouseup docs above actually have a good canvas example
上面的 mouseup 文档实际上有一个很好的画布示例
回答by Phrogz
I would actually wrap the canvas iff needed to track these commands. Here's a simple example tracking only for a few methods:
我实际上会包装跟踪这些命令所需的画布。这是一个简单的示例,仅针对几种方法进行跟踪:
function eventOnDraw( ctx, eventName ){
var fireEvent = function(){
var evt = document.createEvent("Events");
evt.initEvent(eventName, true, true);
ctx.canvas.dispatchEvent( evt );
}
var stroke = ctx.stroke;
ctx.stroke = function(){
stroke.call(this);
fireEvent();
};
var fillRect = ctx.fillRect;
ctx.fillRect = function(x,y,w,h){
fillRect.call(this,x,y,w,h);
fireEvent();
};
var fill = ctx.fill;
ctx.fill = function(){
fill.call(this);
fireEvent();
};
}
...
var myContext = someCanvasElement.getContext('2d');
someCanvasElement.addEventListener( 'blargle', myHandler, false );
eventOnDraw( myContext, 'blargle' );
回答by Ashwin
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/
在这里小提琴 - http://jsfiddle.net/ashwyn/egXhT/2/
Check for text //Event if Drawnand you will understand where.
检查文本//Event if Drawn,你就会明白在哪里。

