0

I want to draw a certain path step by step, with a certain time period between any two steps.

The code I have for now is

let canvas = document.getElementById("c");
let ctx = canvas.getContext('2d');

let p = 'M10 10 h 80 v 80 h -80 Z';
let pathArr = ["M10", "10 h", "80 v", "80 h", "-80 Z"];
let lgt = pathArr.length;
let i = 0;

(function draw() {
    if(i < lgt){
        let pathElem = new Path2D(pathArr[i]);
        ctx.stroke(pathElem);
        i++;
        setTimeout(draw, 200);
    }
})();

The intended function is to make what ctx.stroke(p) would do, but step by step, like stroking the elements of pathArr one at a time, with a delay of 200ms between every two strokes.

But, this code doesn't work as intended. What am I doing wrong, and what should I do to make it work as desired?

Eagle
  • 318
  • 4
  • 16
  • Does this answer your question? [How can I animate the drawing of text on a web page?](https://stackoverflow.com/questions/29911143/how-can-i-animate-the-drawing-of-text-on-a-web-page) – Peter O. Jan 05 '20 at 15:27
  • @PeterO. I've tried that, but I didn't get a good enough resolution using that – Eagle Jan 05 '20 at 15:32
  • @Eagle *"...good enough resolution..."* What!! 2D context renders to sub-pixel resolutions. Both `lineDashOffset` and `setLineDash` accept floating point numbers and 2D context will render strokes at sub pixel resolution. Eg `ctx.setLineDash([0.1, 3,])` will show barely visible pixels that visibly appear to move at offset steps of 0.1. What do you mean by "resolution"??? – Blindman67 Jan 05 '20 at 16:51

0 Answers0