canvas imgQueue isPointInPath

1.绘制canvas的时候,某次引用了外部img对象,循环加载,然后绘制,发现老是闪烁。

后来就发明了img队列,imgQueue函数,等待所有img全部Load完毕,再去绘制.

imgQueue: function(cache, callback, imgs) {
var imgs = imgs || [],
one = cache.shift(),
__self__ = arguments.callee,
img = new Image();
img.src = one.src;
img.onload = function() {
imgs.push([img, one]);
if (cache.length > 0) {
__self__(cache, callback, imgs);
} else {
if (callback) {
callback(imgs);
}
}
}
},


2.在绘制canvas的时候,经常需要进行交互,canvas没有提供内部元素获取的api,所以不能直接添加事件,这个时候内置函数isPointInPath就发挥作用了。

附上代码片段:

drawNet: function(net, x, y) {
var ctx = this.config.canvas.getContext("2d");
if (net.x && net.y) {
ctx.beginPath();
ctx.moveTo(net.x, net.y);
ctx.arc(net.x, net.y, this.config.node.r, 0, Math.PI * 2, true);
if (ctx.isPointInPath(x, y)) {
this.config.__global__.active = net;
}
ctx.closePath();
ctx.strokeStyle = "#fff";
ctx.lineWidth = "8";
if (net.nodes.length > 0) {
ctx.fillStyle = "#223366";
} else {
ctx.fillStyle = "#990000";
}
ctx.stroke();
ctx.fill();
}
if (net.nodes.length > 0) {
for (var i = 0, l = net.nodes.length; i < l; i++) {
arguments.callee.call(this, net.nodes[i], x, y);
}
}
},



原文地址:https://www.cnblogs.com/jiajiaobj/p/2404551.html