Я анимирую значение для strokeStyle от черного rgb(0,0,0)
до белого rgb(255,255,255)
.Для перехода от черного к серому к белому обратно к серому и черному снова я использую Math.abs(Math.sin(H)) * 255;
Вместо использования setInterval
я использую requestAnimationFrame
Также я перевожу контекст, потому что хотел увидеть строку, но вы можете удалить эту часть.
var c = document.getElementById("myCanvas");
c.width = 400;
c.height = 400;
var ctxfii = c.getContext("2d");
// I'm translating the context because I want to see the line;
ctxfii.translate(-600,-400)
ctxfii.strokeStyle = "black";
drawLine();
let H = 0;
function colorChange () {
requestAnimationFrame(colorChange);
H+= .01;
let h = Math.abs(Math.sin(H)) * 255;
//delete everithing on the canvas
ctxfii.clearRect(0,0,c.width,c.height)
// I'm animating the strokeStyle from black: rgb(0,0,0) to white: rgb(255,255,255)
ctxfii.strokeStyle = `rgb(${h},${h},${h})`;
//redraw the line:
drawLine();
};
colorChange()
// a function to draw the line; I'll need this function more than once
function drawLine(){
ctxfii.beginPath();
ctxfii.moveTo(700, 415);
ctxfii.lineTo(700, 515);
ctxfii.lineWidth = 1;
ctxfii.stroke();
}
canvas{border:1px solid;background:skyblue;}
<canvas id="myCanvas"></canvas>