0

我有这个片段,它使用 CSS 将整页<canvas>元素放入 45 度视角。但是,转换后的画布超出了页面的边界并被剪裁:

window.onload = window.onresize = function() {
  // draw a gradient on the canvas
  var canvas = document.querySelector('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  var ctx = canvas.getContext('2d');
  var grad = ctx.createLinearGradient(0, 0, 0, canvas.height);
  grad.addColorStop(0, '#ff0000');
  grad.addColorStop(0.5, '#ffff00');
  grad.addColorStop(1, '#00ff00');
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
};
body {
  margin: 0;
  overflow: hidden;
}

canvas {
  transform-style: preserve-3d;
  transform: rotateX(45deg);
}

.container {
  width: 100%;
  height: 100%;
  perspective: 50vw;
  perspective-origin: 50% 0%;
}
<div class="container">
  <canvas></canvas>
</div>

我如何确保整个画布保持在页面边界内(梯形的底部应该与页面具有完全相同的宽度),同时保持透视效果?CSS 或 JavaScript 解决方案都可以,只要它们适用于任何页面大小。

4

1 回答 1

0

使用向后翻译它translateZ

在 CSS 中查找注释

window.onload = window.onresize = function() {
  // draw a gradient on the canvas
  var canvas = document.querySelector('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  var ctx = canvas.getContext('2d');
  var grad = ctx.createLinearGradient(0, 0, 0, canvas.height);
  grad.addColorStop(0, '#ff0000');
  grad.addColorStop(0.5, '#ffff00');
  grad.addColorStop(1, '#00ff00');
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
};
body {
  margin: 0;
  overflow: hidden;
}

canvas {
  transform-style: preserve-3d;
  /* added translation here */
  transform: translateZ(-50vmax) rotateX(45deg);
}

.container {
  width: 100%;
  height: 100%;
  perspective: 50vw;
  perspective-origin: 50% 0%;
  
}
<div class="container">
  <canvas></canvas>
</div>

于 2018-08-11T17:41:25.440 回答