【问题标题】:Cut Image In Grid And Flip It在网格中剪切图像并翻转它
【发布时间】:2014-05-25 15:13:47
【问题描述】:

示例图片:

*抱歉,实际上网格的大小不正确,仅举例说明。

如何根据网格进行切割并翻转?其实我想要的是翻转后,它会显示这样的内容:

我该怎么做?我希望我不需要剪切所有图像,如果可以的话,只需放置墙纸,它就会自动剪切。

【问题讨论】:

标签: jquery html css


【解决方案1】:

使用background-position 是一种众所周知的将图像分割成小块的方法。通过该技术,您可以逐步解决您的问题。我已经尝试过这段代码来演示技术并解决您的问题。

HTML

<div class='canvas'></div>

CSS

.canvas {
  background:url('http://placekitten.com/500/300');
  width:500px;
  height:300px;
}
.cell {    
  float:left;    
  position:relative;
  cursor:pointer;
}
.cell > .front {            
  -webkit-backface-visibility: hidden; 
  backface-visibility:hidden;
  -webkit-transform-style:preserve-3d;
  transition:all 1s;
}
.cell:not(.flipped) > .back {
  -webkit-transform:rotateY(180deg);
}
.cell.flipped > .front {
  -webkit-transform:rotateY(180deg);
}
.back {
  background:pink;
}
.cell > .back {
  position:absolute;
  text-align:center;
  font-size:30px;
  color:red;    
  left:0;
  top:0;    
  transition:all 1s;    
}
.cell > .back:before {
  content:'';
  display:inline-block;
  height:100%;
  vertical-align:middle;
}
.cell > * {
  border: 1px solid orange;    
  box-sizing:border-box; 
  width:100%;
  height:100%; 
}

JS

//get the canvas
var canvas = $('div.canvas');
var backgroundImage = canvas.css('background-image');
//remove the background from canvas
canvas.css('background-image','none');
//number of columns and rows
var col = 8;
var row = 4;
var colWidth = canvas.width() / col;
var rowHeight = canvas.height() / row;
//loop through the cells
for(var i = 0; i < row; i++){
  for(var j = 0; j < col; j++){
    //append new cell to canvas
    var cell = $("<div class='cell flipped'><div class='back'>?</div><div class='front'></div></div>")
               .width(colWidth).height(rowHeight).appendTo(canvas);
    //set the background for the cell
    //note that calculate the em unit for more flexible
    //font-size
    cell.find('.front')
        .css('background',backgroundImage)
        .css('background-position', -(j * colWidth) + 'px ' + -(i * rowHeight) + 'px');
    //register click handler for the cell
    cell.click(function(){$(this).toggleClass('flipped')});
  }
}

注意:请在基于 webkit 的浏览器中测试演示,我刚刚为基于 webkit 的浏览器添加了前缀(对于backface-visibilitytransform,...)。另请注意,此代码并不完整,它只是帮助您开始满足您的实际需求。

关于 CSS 的一点解释,实际上你需要在一个单元格上有 2 个面,.front.back 面,.front 用于渲染图像,.back 用于渲染文本(在单元格之后翻转)。在翻转状态下,.front 应围绕Y 轴(垂直轴)旋转180deg,但其backface-visibility 应设置为hidden。相反,.back 应该在正常状态下围绕 Y 轴旋转180deg

Demo.

更新:有些浏览器不支持backface-visibility 功能(例如Maxthon),所以你有另一个漂亮的解决方法是使用@ 987654341@ 代替。在翻转状态下,.back 应该有更高的z-index(例如1)来覆盖.front,而在正常状态下,它应该有一个零z-index,以便它隐藏在.front 后面.这是Updated Demo在不支持backface-visibility的浏览器上工作)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2011-10-05
    • 2015-07-07
    • 2019-08-06
    • 2021-03-24
    • 2013-04-05
    相关资源
    最近更新 更多