javascript – 如何通过z-index对这些canvas元素进行排序?
作者:互联网
我想将这些画布合并到顶部有最大z-index的画布上.
<div id="sketchpad_container">
<canvas id="sketchypad_layer_0" style="z-index: 20; " width="800" height="600">Your browser does not support canvas</canvas>
<canvas id="sketchypad_layer_1" style="z-index: 10; " width="800" height="600">Your browser does not support canvas</canvas>
<canvas id="sketchypad_layer_2" style="z-index: 30; " width="800" height="600">Your browser does not support canvas</canvas>
</div>
给定任意数量的这样的画布层我想按z-index排序,然后使用drawImage将它们组合成一个图像以便导出它.是否有一个简单的按z-index排序?
编辑 – 我按照建议尝试了排序功能,但似乎没有用.
这是我的控制台输出:
$("#sketchpad_container canvas"); //see what's in the collection
//console output gives back (you'll notice z-indices are 40, 20, 10, 30)
[
<canvas id="sketchypad_interactive_layer" class="sketchypad_sketch_layer" style="z-index:40" width="800" height="600">Your browser does not support canvas</canvas>,
<canvas id="sketchypad_layer_0" class="sketchypad_sketch_layer" style="z-index: 20; " width="800" height="600">Your browser does not support canvas</canvas>,
<canvas class="sketchypad_sketch_layer" width="800" height="600">,
<canvas id="sketchypad_layer_1" class="sketchypad_sketch_layer" style="z-index: 10; " width="800" height="600">Your browser does not support canvas</canvas>,
<canvas id="sketchypad_layer_2" class="sketchypad_sketch_layer" style="z-index: 30; " width="800" height="600">Your browser does not support canvas</canvas>
]
//next try to sort the collection
$("#sketchpad_container canvas").toArray().sort(function(a,b){a.style.zIndex - b.style.zIndex});
//but array is still the same order of z-index 40, 20, 10, 30.
// I was expecting 40,30,20,10
[
<canvas id="sketchypad_interactive_layer" class="sketchypad_sketch_layer" style="z-index:40" width="800" height="600">Your browser does not support canvas</canvas>,
<canvas id="sketchypad_layer_0" class="sketchypad_sketch_layer" style="z-index: 20; " width="800" height="600">Your browser does not support canvas</canvas>,
<canvas class="sketchypad_sketch_layer" width="800" height="600">,
<canvas id="sketchypad_layer_1" class="sketchypad_sketch_layer" style="z-index: 10; " width="800" height="600">Your browser does not support canvas</canvas>,
<canvas id="sketchypad_layer_2" class="sketchypad_sketch_layer" style="z-index: 30; " width="800" height="600">Your browser does not support canvas</canvas>
]
我究竟做错了什么?
再次编辑 – 哦,没关系.我需要包含一个“返回”声明. GAH!
解决方法:
假设所有canvas元素都有一个指定的样式值来设置它们的z-index,你可以得到一个由z-index排序的所有canvas元素的数组,如下所示:
var items = $("#sketchpad_container canvas").toArray();
items.sort(function(a, b) {
return(Number(a.style.zIndex) - Number(b.style.zIndex));
});
然后,您可以通过调用每个调用drawImage()的数组进行迭代.对于正确的z阶渲染,您将首先绘制后面的图像(最低的z-index项),按照上面的排序,这意味着您从数组的开头到结尾绘制.
标签:javascript,jquery,sorting,canvas,z-index 来源: https://codeday.me/bug/20190726/1540417.html