How to position element in the correct 3d position with css perspective

时光总嘲笑我的痴心妄想 提交于 2020-01-11 11:38:51

问题


I'm trying to find a way to map an element, on top of a photo element that is placed at a given angle. The photo of a laptop is a good example, where I'd like to map an element (video, image, or other) on top of the screen, for example, let's say to loop a video etc.

The task seemed quite easy but I'm finding it quite tricky, because I couldn't find how to solve it properly with transforms rotate, scale, translate and even skew.

Here's a code example of what I want to achieve, the over element is the SPAN coloured green

Html:

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <span></span>
    <img src="http://www.thesugarrefinery.com/wp-content/uploads/2015/08/sugar-macbook-7-5-perspective.png" />
  </div>

</body>
</html>

css:

div {
  position: relative;
}
span {
  background: green;
  width: 350px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  perspective: 250px;
  transform: rotateX(0deg) rotateY(40deg) rotateZ(0deg) skewX(-10deg) translateX(220px) translateY(25px) scale(.94);
  opacity: 0.5;
}
img {
  width: 500px;
  height: auto;
}

And the snippet:

div {
  position: relative;
}
span {
  background: green;
  width: 350px;
  height: 200px;
  position: absolute;
  top: 0;
  left: 0;
  perspective: 250px;
  transform: rotateX(0deg) rotateY(40deg) rotateZ(0deg) skewX(-10deg) translateX(220px) translateY(25px) scale(.94);
  opacity: 0.5;
}
img {
  width: 500px;
  height: auto;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <span></span>
    <img src="https://i.stack.imgur.com/iL2xf.png" />
  </div>
  
</body>
</html>

回答1:


perspective needs to be added to the parent, not to the child. The rest are details:

span {
  background: green;
  width: 256px;
  height: 176px;
  position: absolute;
  top: 0;
  left: 0;
  transform: rotateX(1deg) rotateY(-7deg) rotateZ(-1deg) skew(-11.25deg, 1.5deg) translate(233px, 37px);
  opacity: 0.5;
}

div {
  position: relative;
  perspective: 400px;
  width: 1200px;
}

img {
  width: 500px;
  height: auto;
}

body {
  overflow-x: hidden;
}
<div>
  <span></span>
  <img src="https://i.stack.imgur.com/iL2xf.png" />
</div>


来源:https://stackoverflow.com/questions/48777549/how-to-position-element-in-the-correct-3d-position-with-css-perspective

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!