在HTML5画布中,是否可以设置绘制对象的z-index?
我正在尝试让一个对象在“玩家”前面,另一个对象在“玩家”后面。
在HTML5画布中,是否可以设置绘制对象的z-index?
我正在尝试让一个对象在“玩家”前面,另一个对象在“玩家”后面。
是的,有点是。您可以使用globalCompositeOperation在现有像素“后面绘制”。
ctx.globalCompositeOperation='destination-over';
这里有一个示例和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cx=100;
drawCircle()
cx+=20;
ctx.globalCompositeOperation='destination-over';
$("#test").click(function(){
drawCircle();
cx+=20;
});
function drawCircle(){
ctx.beginPath();
ctx.arc(cx,150,20,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=randomColor();
ctx.fill();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="test">Draw new circle behind.</button><br>
<canvas id="canvas" width=300 height=300></canvas>
toString(16)
- 你教会了我一个新技巧 :) - Mike或者您可以使用包含要绘制对象的数组,然后使用每个子项的 zIndex
属性对该数组进行排序。然后您只需迭代该数组并绘制子项即可。
var canvas = document.querySelector('#game-canvas');
var ctx = canvas.getContext('2d');
// Define our shape "class".
var Shape = function (x, y, z, width, height) {
this.x = x;
this.y = y;
this.zIndex = z;
this.width = width;
this.height = height;
};
// Define the shape draw function.
Shape.prototype.draw = function () {
ctx.fillStyle = 'lime';
ctx.fillRect(this.x, this.y, this.width, this.height);
};
// let's store the objects to be drawn.
var objects = [
new Shape(10, 10, 0, 30, 30), // should be drawn first.
new Shape(50, 10, 2, 30, 30), // should be drawn third.
new Shape(90, 10, 1, 30, 30) // should be drawn second.
];
// For performance reasons, we will first map to a temp array, sort and map the temp array to the objects array.
var map = objects.map(function (el, index) {
return { index : index, value : el.zIndex };
});
// Now we need to sort the array by z index.
map.sort(function (a, b) {
return a.value - b.value;
});
// We finaly rebuilt our sorted objects array.
var objectsSorted = map.map(function (el) {
return objects[el.index];
});
// Now that objects are sorted, we can iterate to draw them.
for (var i = 0; i < objectsSorted.length; i++) {
objectsSorted[i].draw();
}
// Enjoy !
map.sort(function (a, b) { return a - b; });
应该改为 map.sort(function (a, b) { return a.value - b.value; });
,我认为你不能只是减去两个对象。 - dud3首先,先画出它后面的物体,然后是这个物体,最后是其他物品。
要进行命中测试,您可能需要反向迭代您的显示列表,逐个测试每个对象。如果您非常了解对象边界,则可以使用此方法。
或者,您可能想尝试一些标准的图形技巧,比如将相同的对象绘制到另一个内存画布上,并为每个绘制的对象使用唯一的颜色:要进行命中测试,只需检查内存画布上的像素颜色。很不错吧 ;-)
<canvas id="background-canvas" height="500" width="1000" style="border:1px solid #000000;"></canvas>
<canvas id="player-canvas" height="500" width="1000" style="border:1px solid #000000;"></canvas>
<canvas id="hud-canvas" height="500" width="1000" style="border:1px solid #000000;"></canvas>
抱歉,画布元素将有它的z-index,任何在其上绘制的内容都将在该层上。
如果您是指画布上的不同元素,则是的,任何绘制的东西都是绘制在之前所有内容的顶部。