要实时刷新画面的话,要使用 requestAnimationFrame 方法,传入一个刷新方法,就会在每帧进行调用刷新。
    关于requestAnimationFrame 的介绍:
    CSS3动画那么强,requestAnimationFrame还有毛线用? « 张鑫旭-鑫空间-鑫生活
    你需要知道的requestAnimationFrame - 掘金


    官方的 Ink 代码调整后:

    1. function starPath(CanvasKit: ICanvasKit, X: number, Y: number, R = 128) {
    2. const p = new CanvasKit.SkPath();
    3. p.moveTo(X + R, Y);
    4. for (let i = 1; i < 8; i++) {
    5. const a = 2.6927937 * i;
    6. p.lineTo(X + R * Math.cos(a), Y + R * Math.sin(a));
    7. }
    8. return p;
    9. }
    10. const init = async () => {
    11. const CanvasKit = await CanvasKitInit();
    12. const dom = document.getElementById('test') as HTMLCanvasElement | null;
    13. if (!dom) {
    14. console.log('loading...');
    15. return;
    16. }
    17. const surface = CanvasKit.MakeCanvasSurface(dom);
    18. const canvas = surface.getCanvas();
    19. const paint = new CanvasKit.SkPaint();
    20. const textPaint = new CanvasKit.SkPaint();
    21. textPaint.setColor(CanvasKit.Color(40, 0, 0, 1.0));
    22. textPaint.setAntiAlias(true);
    23. const textFont = new CanvasKit.SkFont(null, 30);
    24. let offset = 0;
    25. let X = 250;
    26. let Y = 250;
    27. const context = CanvasKit.currentContext();
    28. function drawFrame() {
    29. // If there are multiple contexts on the screen, we need to make sure
    30. // we switch to this one before we draw.
    31. CanvasKit.setCurrentContext(context);
    32. const path = starPath(CanvasKit, X, Y);
    33. // const dpe = CanvasKit.MakeSkDashPathEffect([15, 5, 5, 10], offset / 5);
    34. offset++;
    35. // paint.setPathEffect(dpe);
    36. paint.setStyle(CanvasKit.PaintStyle.Stroke);
    37. paint.setStrokeWidth(5.0 + -3 * Math.cos(offset / 30));
    38. paint.setAntiAlias(true);
    39. paint.setColor(CanvasKit.Color(66, 129, 164, 1.0));
    40. canvas.clear(CanvasKit.Color(255, 255, 255, 1.0));
    41. canvas.drawPath(path, paint);
    42. canvas.drawText('Try Clicking!', 10, 425, textPaint, textFont);
    43. canvas.flush();
    44. // dpe.delete();
    45. path.delete();
    46. requestAnimationFrame(drawFrame);
    47. }
    48. requestAnimationFrame(drawFrame);
    49. // Make animation interactive
    50. dom.addEventListener('pointermove', e => {
    51. if (!e.pressure) {
    52. return;
    53. }
    54. X = e.offsetX;
    55. Y = e.offsetY;
    56. });
    57. };
    58. export default (): React.ReactNode => {
    59. useEffect(() => {
    60. init();
    61. }, []);
    62. return (
    63. <div>
    64. <canvas id="test" width="1000" height="800" />
    65. </div>
    66. );
    67. };

    其实到这一步为止 CanvasKit 的用法基本上已经清楚了,接来下比较重要的应该是做上层封装。