HTML5 Canvas redraw-cycle performance optimisations

前端 未结 2 534
情歌与酒
情歌与酒 2020-12-13 05:57

We are building a CAD app that runs in a browser.

  • C.A.D stands for Computer Aided Design.
  • Illustrator, CorelDraw, AutoCAD etc are some examples of CA
2条回答
  •  攒了一身酷
    2020-12-13 06:11

    Useful tool

    My branch of paper.js could help, but it is maybe not the best fit for you.

    It enables you to prevent paper.js to redraw everything every frames (use paper.view.persistence = 1;).

    This way you have better control over what to clear and should be redrawn: for example when you move a shape, you can clear the area where it was (using native canvas drawRect for instance), and update it once it is moved (use path.needsUpdate();).

    Drawback

    The problems come when shapes intersect. If you want to modify a shape which intersect another one, you will have to update both. Same thing if the second shape intersects a third one, and so one and so forth.

    So you need a recursive function, not hard to code, but it can be costly if there are many complexe shapes intersecting, and so you might not gain performances in this case.

    (Update) Bitmap caching

    As suggested by Nicholas Kyriakides in the following answer, Bitmap caching is a very good solution.

    One canvas per shape

    An alternative would be to draw each shape on a separate canvas (working as layers). This way you can freely clear and redraw each shape independently. You can detach the onFrame event of the views which are not changing (all canvas except the one on which the user is working). This should be easier, but it leads to other small problems such as sharing the same project view parameters (in the case of zoom), and it might be costly with many shapes (which means many canvas).

    Static and dynamic canvas

    A (probably) better approach would be to have only two canvas, one for the static shapes, and one for the active shape. The static shapes canvas would contain all shapes (except the one being edited) and would be redrawn just when the user start and stop editing the active shape. When the user starts editing a shape it would be transferred from the static canvas to the dynamic one, and the the other way when the user stops.

提交回复
热议问题