> 在開發中,如果要使用一個背景圖,可能需要加載幾十到一兩百KB的圖片,無疑是耗費流量,延遲了頁面的展現。如果僅僅是純色或者規則漸變的背景,完全可以用canvas來實現。
>[info] 效果圖如下:
可拆解為--矩形+弧形區填充+弧線

~~~
具體代碼(全部復制到.html文件里就可在瀏覽器打開):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas_Background</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
<style type="text/css">
html, body{
margin: 0; padding: 0;
}
#canvas_wrap {
width: 100%;
height: 100vh;
}
#canvas {
position: absolute;
z-index: -1;
}
</style>
</head>
<div id="canvas_wrap">
<canvas id="canvas"></canvas>
</div>
<body>
<script type="text/javascript">
let parentDiv = document.getElementById('canvas_wrap').getBoundingClientRect(),
offsetW = parentDiv.width,
offsetH = parentDiv.height,
canvasEle = document.getElementById('canvas'),
ctx = canvasEle.getContext('2d'),
grd = ctx.createLinearGradient(0, 0, offsetW, 0);
canvasEle.setAttribute('width', offsetW);
canvasEle.setAttribute('height', offsetH);
grd.addColorStop(0, '#4AAAF9'); // 開始顏色
grd.addColorStop(1, '#2F4EFE'); // 結束顏色
// 繪制矩形部分
ctx.fillStyle = grd; // 填充使用自定義的漸變規則
ctx.fillRect(0, 0, offsetW, 200);
// 繪制弧形部分
ctx.beginPath();
ctx.moveTo(0, 200);
ctx.quadraticCurveTo(offsetW / 2, 600, offsetW, 200);
ctx.fill();
// 繪制弧線
ctx.moveTo(0, 200);
ctx.quadraticCurveTo(offsetW / 2, 660, offsetW, 300);
ctx.strokeStyle = grd;
ctx.lineWidth = 1.5;
ctx.stroke();
</script>
</body>
</html>
~~~