在画布中使用JavaScript在图像对象上添加样式

在画布中使用JavaScript在图像对象上添加样式,javascript,canvas,html5-canvas,Javascript,Canvas,Html5 Canvas,我正在尝试在图像上添加z索引。我还使用了setAttribute,但样式不起作用。请找出问题所在 // Hero image var heroReady = false; var heroImage = new Image(); heroImage.onload = function () { heroReady = true; }; heroImage.setAttribute("src", "img/car.png"); heroImage.setAttribute("style"

我正在尝试在图像上添加z索引。我还使用了setAttribute,但样式不起作用。请找出问题所在

// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};

heroImage.setAttribute("src", "img/car.png");
heroImage.setAttribute("style", "z-index:5;");
你应该使用“风格”

这是玩的

片段:

var div=document.getElementById(“某物”); div.style.position=“绝对”; div.style.width=“200px”; div.style.height=“200px”; div.style.backgroundColor=“蓝色”; div.style.zIndex=“2”; 函数onClick(){ (div.style.zIndex==“2”)?div.style.zIndex=“0”:div.style.zIndex=“2”; }
#另一个{
z指数:1;
宽度:180px;
高度:180像素;
背景颜色:绿色;
位置:绝对位置;
}
钮扣{
左边距:200px;
}
什么 另一个
更改zIndex当您说,您正在尝试添加z索引时,是否使用画布绘制此图像?或者您指的是CSS样式吗?对于给定的代码,您的图像永远不会附加到文档中,
heroReady
不指任何内容,[canvas]标记也不相关。@canvas是的,我正在使用Canvas@Kaiido代码对我来说运行良好。。只是我需要申请z-index@MuhammadRehman如果您使用的是画布,只需先绘制背景图像,然后绘制前景图像,例如
canvas.drawImage(backgroundSprite,0,0);画布,drawImage(英雄法师,100100)你把你的图像分层,这样你画的第一个图像总是在你画的最后一个前景图像的后面。我想他没有要求这个。。。但这样做更正确。
heroImage.style.zIndex = "5";