translateZ()vs scale()中的CSS错误渲染

时间:2015-09-17 10:27:06

标签: css css3 css-transforms antialiasing

我注意到在以这两种方式转换文本时存在很大的质量差异:

.text1 {
  width: 200px;
  height: 22px;
  position: absolute;
  top: 40%;
  left: 0;
  transform-origin: 50% 50%;
  transform: scale(2); /* here */
  color: red;
  text-align: center;
  font-size: 22px;
}
.text2 {
  width: 200px;
  height: 22px;
  position: absolute;
  top: 60%;
  left: 0;
  transform-origin: 50% 50%;
  transform: translateZ(400px); /* here */
  text-align: center;
  font-size: 22px;
}
.perspective {
  width: 200px;
  height: 200px;
  perspective: 800px;
  transform-style: preserve-3d;
}
<div class="perspective">
  <div class="text1">Text</div>
  <div class="text2">Text</div>
</div>

当在Z轴上移动文本时,有没有办法强制渲染更好的渲染?

2 个答案:

答案 0 :(得分:11)

当您使用translateZ(400px)进行转换时,文字模糊的原因是这是3D转换;浏览器将元素视为纹理而不是向量,以提供硬件3d加速 因此,当增加尺寸时,分辨率基本上会降低。

另一方面,使用缩放进行转换是2D转换, 浏览器将元素视为向量,并且不会出现模糊。

在我们开始使用3d时,看看scale会发生什么,而不实际设置任何translateZ值:

&#13;
&#13;
.text1 {
    width: 200px;
    height: 22px;
    position: absolute;
    top: 40%;
    left: 0;
    transform-origin: 50% 50%;
    transform: scale(2);
    /* here */
    color: red;
    text-align: center;
    font-size: 22px;
}
.text1a {
    width: 200px;
    height: 22px;
    position: absolute;
    top: 40%;
    left: 50%;
    transform-origin: 50% 50%;
    transform: translateZ(0) scale(2);
    /* here */
    color: blue;
    text-align: center;
    font-size: 22px;
}
.text2 {
    width: 200px;
    height: 22px;
    position: absolute;
    top: 60%;
    left: 0;
    transform-origin: 50% 50%;
    transform: translateZ(400px);
    /* here */
    text-align: center;
    font-size: 22px;
}
.perspective {
    width: 200px;
    height: 200px;
    perspective: 800px;
    transform-style: preserve-3d;
}
&#13;
<div class="perspective">
    <div class="text1">Text</div>
    <div class="text1a">Text</div>
    <div class="text2">Text</div>
</div>
&#13;
&#13;
&#13;

我现在能想到的唯一解决方法是通过JS检查样式表并使用translateZ覆盖transform: scale

var styles = document.styleSheets;

//patterns
var perspPat = /perspective\s*?:\s*?(\d+)/;
var transZPat = /translateZ\(\s*?(\d+)/;

var perspective;
var translateZ = [];
[].slice.call(styles).forEach(function (x) {
    [].slice.call(x.rules).forEach(function (rule) {
        if (perspPat.test(rule.cssText)) {
            perspective = perspPat.exec(rule.cssText)[1]
        };
        if (transZPat.test(rule.cssText)) {
            translateZ.push([
            rule.selectorText,
            transZPat.exec(rule.cssText)[1]]);
        }


    });

})


translateZ.forEach(function (x) {
    document.querySelector(x[0]).style.transform = 'scale(' + perspective / x[1] + ')';

})

fiddle

正如您所看到的,即使它确实有效,也需要进行大量优化。 (我不会认为它的生产准备就绪了。)

答案 1 :(得分:-1)

您可以为webkit添加font-smooth(对于firefox)和antialiasing

 .text2 {
    -webkit-font-smoothing: antialiased;
    font-smooth: always;
 }

https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth

http://davidwalsh.name/font-smoothing

相关问题