如何制作ctx.stroke()的动画?

时间:2019-01-04 14:42:51

标签: javascript canvas

我有一组坐标(x,y,t)。 x和y代表2D空间上的位置,t是它们出现的时间(以ms为单位)

对于每个点,我都画一个矩形,然后画一条线到下一个。

按照矩形的出现时间,矩形确实一个接一个地出现。这些行没有。

我尝试使用setTimeout,setInterval和requestAnimationFrame。我经常遇到哪个问题都没关系

以下是播放动画的代码:

df %>% 
 setNames(as.character(df[1,])) %>%
 rowid_to_column() %>%
 gather(var, val, -rowid) %>%
 mutate(val = ifelse(val == var, 1, 0)) %>%
 spread(var, val) %>%
 filter(rowid != 1) %>%
 select(-rowid)

  Car Cat Hat
1   0   1   0
2   0   0   1
3   1   0   0

这是虚拟数据:

let i = 0; // i represents the time
const iterate = function () {
    if (i > max_t) { // when i has reached the last point in time, the function stops
        return;
    }

    data.forEach(function (e, j) { // data is an array of set of (x,y,t) coordinates

        if (e.interval[indexes[j]] == i) { // e.interval[indexes[j]] is t mentioned earlier
            indexes[j]++; // increment the pointer so we can draw the next point

            ctx.fillStyle = "#000000"; // this part is where we plot the dots and draw the lines
            let plot_x = middle_width + (e.x[indexes[j]]);
            let plot_y = middle_height + (e.y[indexes[j]]);

            ctx.strokeStyle = colors[j];
            if (indexes[j] > 0) { // this doesn't seem to wait for the timeout to execute
                ctx.moveTo(plot_x, plot_y);
                ctx.lineTo(middle_width + e.x[indexes[j] - 1], middle_height + e.y[indexes[j] - 1]);
                ctx.stroke();
            }

            ctx.fillRect(plot_x - 3, plot_y - 3, 6, 6); // but this does seem to wait for the timeout to execute
            ctx.fillStyle = colors[j];

            ctx.fillRect(plot_x - 2, plot_y - 2, 4, 4);
        }
    });
    i++;
    window.setTimeout(iterate, 1);
};
window.setTimeout(iterate, 1);

结果如下:点与时间一起绘制。但是这些行没有,这是一个gif:https://imgur.com/a/jAtsk5q

谢谢

0 个答案:

没有答案