JavaScript折页特效
时间: 2023-10-28 16:05:52 浏览: 70
实现 JavaScript 折页特效可以使用 CSS3 动画和 jQuery 的事件绑定,同时需要用到 HTML 的 `<canvas>` 标签。
首先,在 HTML 中创建一个 `<canvas>` 标签并设置宽高:
```html
<canvas id="fold-canvas" width="300" height="200"></canvas>
```
然后,在 JavaScript 中获取 canvas 对象,并创建一个用于绘制的 2D 上下文:
```javascript
var canvas = document.getElementById('fold-canvas');
var ctx = canvas.getContext('2d');
```
接着,创建一个用于绘制折叠效果的函数:
```javascript
function drawFold() {
var width = canvas.width;
var height = canvas.height;
var halfWidth = width / 2;
var halfHeight = height / 2;
var foldWidth = 50; // 折叠宽度
var foldHeight = 20; // 折叠高度
var angle = Math.PI / 4; // 折叠角度
var gradient = ctx.createLinearGradient(0, 0, width, 0); // 创建渐变
// 设置渐变颜色
gradient.addColorStop(0, 'rgba(0,0,0,0)');
gradient.addColorStop(0.45, 'rgba(0,0,0,0)');
gradient.addColorStop(0.5, 'rgba(0,0,0,0.5)');
gradient.addColorStop(0.55, 'rgba(0,0,0,0)');
gradient.addColorStop(1, 'rgba(0,0,0,0)');
// 绘制左侧区域
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(halfWidth - foldWidth, 0);
ctx.lineTo(halfWidth, halfHeight - foldHeight);
ctx.lineTo(halfWidth, halfHeight + foldHeight);
ctx.lineTo(halfWidth - foldWidth, height);
ctx.lineTo(0, height);
ctx.closePath();
ctx.fillStyle = gradient;
ctx.fill();
// 绘制右侧区域
ctx.beginPath();
ctx.moveTo(halfWidth + foldWidth, 0);
ctx.lineTo(width, 0);
ctx.lineTo(width, height);
ctx.lineTo(halfWidth + foldWidth, height);
ctx.lineTo(halfWidth, halfHeight + foldHeight);
ctx.lineTo(halfWidth, halfHeight - foldHeight);
ctx.closePath();
ctx.fillStyle = gradient;
ctx.fill();
}
```
最后,在 jQuery 中绑定鼠标移动事件,根据鼠标位置计算折叠角度并重新绘制:
```javascript
$(canvas).mousemove(function(e) {
var x = e.pageX - $(this).offset().left;
var y = e.pageY - $(this).offset().top;
var width = canvas.width;
var height = canvas.height;
var angle = Math.atan2(height - y, x - width / 2);
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.rotate(angle);
drawFold();
ctx.restore();
});
```
这样,当用户在 canvas 区域内移动鼠标时,就会触发折叠效果的动画。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)