# canvas繪製折線路徑動畫

• 需要計算子路徑，這塊計算比較複雜。（當然是可以實現的）
• 漸變的計算， 從圖中可以看出，動畫的子路徑是有漸變效果的，如果要分段計算漸變也很複雜。

## 繪製灰色路徑

`````` ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(230,200);
ctx.lineTo(250,50);
ctx.lineTo(270,180);
ctx.lineTo(300,60);
ctx.lineTo(330,160);
ctx.lineTo(350,60);
ctx.lineTo(380,100);
ctx.lineTo(480,100);
ctx.strokeStyle = "gray";
ctx.lineJoin = "round";
ctx.stroke();
``````

## 繪製亮色路徑

``````ctx.save();
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(230,200);
ctx.lineTo(250,50);
ctx.lineTo(270,180);
ctx.lineTo(300,60);
ctx.lineTo(330,160);
ctx.lineTo(350,60);
ctx.lineTo(380,100);
ctx.lineTo(480,100);
ctx.strokeStyle = "gray";
ctx.lineJoin = "round";
ctx.stroke();
``````

## clip控制亮色路徑的繪製區域

canvas的clip方法可以控制繪製的區域，通過該方法，可以控制智繪製路徑的一部分：

``````        ctx.beginPath();
ctx.rect(offset,0,100,500); // offset 等於0
ctx.clip();
...
ctx.stroke();
``````

clip之後，亮色路徑就只會繪製一部分,如下圖：

## 動畫效果

`````` offset += 2;
if(offset > 600){
offset = 100;
}
requestAnimationFrame(animate);
``````

## 漸變

``````function createGradient(ctx,x0,y0,x1,y1){
return grd;
}

``````

## 全部代碼

``````<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>line animate</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var ctx = document.getElementById( 'canvas' ).getContext( '2d' );
var w = canvas.width,
h = canvas.height;

var x = w / 2,y = h / 2;

function setupCanvas(canvas) {
let width = canvas.width,
height = canvas.height,
dpr = window.devicePixelRatio || 1.0;
if (dpr != 1.0 ) {
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.height = height * dpr;
canvas.width = width * dpr;
ctx.scale(dpr, dpr);
}
}
setupCanvas(canvas);
var offset = 100;
return grd;
}

function animate(){
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.lineWidth = 3;
ctx.save();
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(230,200);
ctx.lineTo(250,50);
ctx.lineTo(270,180);
ctx.lineTo(300,60);
ctx.lineTo(330,160);
ctx.lineTo(350,60);
ctx.lineTo(380,100);
ctx.lineTo(480,100);
ctx.strokeStyle = "gray";
ctx.lineJoin = "round";
ctx.stroke();

ctx.beginPath();
ctx.rect(offset,0,150,500);
ctx.clip();
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(230,200);
ctx.lineTo(250,50);
ctx.lineTo(270,180);
ctx.lineTo(300,60);
ctx.lineTo(330,160);
ctx.lineTo(350,60);
ctx.lineTo(380,100);
ctx.lineTo(480,100);
ctx.lineWidth = 4;
ctx.lineCap = "round";
// ctx.globalCompositeOperation = 'lighter';
ctx.lineJoin = "round";
ctx.stroke();

ctx.restore();

offset += 2;
if(offset > 600){
offset = 100;
}

requestAnimationFrame(animate);
}

animate();
</script>
</body>
</html>
``````