如何在画布中模拟z-index

Jal*_*eri 5 javascript html5 canvas html5-canvas

我之前问了一个问题:如何控制画布对象的z-index?我们找到了一个对复杂情况可能不是一个好的解决方案.

我发现canvas没有z-index系统,而是一个简单的有序绘图系统.现在有一个新问题:我如何模拟z-index系统以在复杂情况下解决这个问题?

好的答案可以解决一个大问题.

Den*_*ret 9

并不是画布没有z索引,而是画布不会使对象与HTML页面相反.它只是利用像素矩阵.

基本上有两种类型的绘图模型:

  • 对象(通常是向量):对象由引擎保存和管理.通常可以删除或更改它们.他们有一个z指数
  • 位图:没有对象.你只需改变一个像素矩阵

Canvas模型是位图模型.要将对象绘制在其他对象上,必须在之后绘制它们.这意味着您必须管理您绘制的内容.

画布模型速度非常快,但如果您想要一个管理对象的绘图系统,可能需要使用SVG.


如果你想使用画布,那么最好是将你绘制的内容保留为对象.这是我刚才做的一个例子:我保留一个正方形列表,每一秒我随机化它们的zindex并重绘它们:

var c = document.getElementById('c').getContext('2d');
function Square(x, y, s, color) {
   this.x = x; this.y = y; this.s = s; this.color = color;
   this.zindex=0;
}
Square.prototype.draw = function(c) {
  c.fillStyle = this.color;
  c.fillRect(this.x, this.y, this.s, this.s);  
}
var squares = [
  new Square(10, 10, 50, 'blue'), new Square(40, 10, 40, 'red'), new Square(30, 50, 30, 'green'),
  new Square(60, 30, 40, '#111'), new Square(0, 30, 20, '#444'), new Square(70, 00, 40, '#999')
];

function draw() {
  c.fillStyle = "white";
  c.fillRect(0, 0, 1000, 500);
  for (var i=0; i<squares.length; i++) squares[i].draw(c);
}
setInterval(function(){
  // give all squares a random z-index
  squares.forEach(function(v){v.zindex=Math.random()});
  // sort the list accordingly to zindex
  squares.sort(function(a,b){return a.zindex-b.zindex});
  draw();
}, 1000);
Run Code Online (Sandbox Code Playgroud)

示范

这个想法是方形数组根据zindex进行排序.这可以很容易地扩展到其他类型的对象.