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

时间:2015-08-16 17:37:35

标签: javascript canvas html5-canvas

我正在尝试在图片上添加z-index。我也使用了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;");

1 个答案:

答案 0 :(得分:1)

你应该使用“风格”。 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

heroImage.style.zIndex = "5";

这里是an example

摘录:

var div = document.getElementById("something");
div.style.position = "absolute";
div.style.width = "200px";
div.style.height = "200px";
div.style.backgroundColor = "blue";
div.style.zIndex = "2";

function onClick() {
  (div.style.zIndex == "2") ? div.style.zIndex = "0" : div.style.zIndex = "2";
}
#another {
  z-index: 1;
  width: 180px;
  height: 180px;
  background-color: green;
  position: absolute;
}

button {
  margin-left: 200px;
}
<div id="something">Something</div>
<div id="another">Another</div>
<button onclick="onClick()">Change zIndex</button>