我想将这些画布合并到顶部有最大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!
答案 0 :(得分:8)
假设所有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项),按照上面的排序,这意味着您将从数组的开头绘制到结束。