我正在从头开始研究HTML5 Canvas对象,所以这个问题的目的仅仅是提高知识。
你可以试试看我的项目:
https://github.com/ISDesign-tv/Canvas
http://jsfiddle.net/IvanSollima/T6YKL/
目标是:
通过清除和绘制,找到一种提高Canvas速度的方法 画布区域中需要更新的部分。
背景:
您可以绘制的每个东西都是多边形,并将其作为对象进行跟踪。 每个对象都有属性,包括顶点位置,线条,边界框,质心 等
我的方法:
当我需要以某种方式删除,拖动或更新对象时, 我将目标对象传递给名为 refresh(poly,callback);
的函数refresh()具有可选参数sPoly和callback。
当使用两个参数调用它时,该函数会查找现有对象的边界框与传递的对象的交叉点,然后返回需要刷新的对象数组。
然后它将结果向量( toWipe )传递给clear函数,该函数实际上清除了每个对象边界框的区域。
然后它再次将向量传递给draw函数,该函数将对象绘制回来。
最后它运行回调;
代码:
//sPoly is the object representing the actual polygon drawn on screen
refresh: function (sPoly, callback){
var toWipe;
//callback is optional
callback = callback || function () {};
//if you passed sPoly in the function call refresh() will
//try to clear just the area of the Canvas that need to be update instead of
//clearing everything
if(sPoly){
//getBBoxIntersect takes an object, and a tolerance value, and returns an
//array of objects that will need to be redrawn as consequence of the
//redraw of the passed object.
toWipe = getBBoxIntersect(sPoly, 5);
//clear all the object in the array toWipe based on each one bounding box.
self.clear(toWipe);
//draw again that objects
self.draw(toWipe);
}else{
self.clearAll();
self.draw(polys);
}
callback();
},
问题是clear函数实际上并没有在重绘之前清除对象边界框,而是在之后。 使用快速鼠标移动拖动对象时,可以轻松地重复该错误。
有没有办法改善我的做法?
如何重复错误:
两个多边形显示其中心和边界框
屏幕以灰色显示javascript在拖动时实际重写的区域,以及一堆错误,其中没有。
您可以看到,当三角形接近正方形时,刷新功能还会更新正方形周围的区域