r1111
r1111

Reputation: 33

How to create a function that changes the color of a single line from black to grey to white?

I have coded a cube using canvas and the <script> tag. I would like to create a function that changes the color of a single line from black to grey to white within a given timeframe.

var c = document.getElementById("myCanvas");
var ctxfii = c.getContext("2d");
ctxfii.beginPath();
ctxfii.moveTo(700, 415);
ctxfii.lineTo(700, 515);
ctxfii.lineWidth = 1;
ctxfii.strokeStyle = "black";
ctxfii.stroke();  

var colorChange = ctxfii;
function colorChange () {
    window.setInterval(10);
    document.getElementById("myCanvas").strokeStyle = "grey"
};

Nothing comes up the whole canvas appears blank.

Upvotes: 0

Views: 44

Answers (1)

enxaneta
enxaneta

Reputation: 33044

I'm animating the value for strokeStyle from black rgb(0,0,0) to white rgb(255,255,255). In order to make it go from black to grey to white back to grey and black again I'm using Math.abs(Math.sin(H)) * 255;

Instead of using setInterval I'm using requestAnimationFrame

Also I'm translating the context because I wanted to see the line, but you can remove this part.

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>

Upvotes: 1

Related Questions