phetsims / shred

A library of JavaScript code that is used in PhET simulations that depict atoms, subatomic particles, and atomic structure. This was originally created to contain the code that is shared between the "Build an Atom" and "Isotopes and Atomic Mass" simulations, thought it may be applied to additional simulations in the future.
GNU General Public License v3.0
1 stars 6 forks source link

Performance for IsotopeCanvasNode.js #8

Closed samreid closed 8 years ago

samreid commented 8 years ago

During today's meeting, @jbphet discussed the performance of IsotopeCanvasNode. The code in question is here:

    paintCanvas: function( context ) {
      var isotope;
      var i;
      for ( i = 0; i < this.isotopes.length; i++ ) {
        isotope = this.isotopes[ i ];
        context.fillStyle = isotope.color._css;
        context.lineWidth = 0.4;
        context.beginPath();
        context.arc( this.modelViewTransform.modelToViewX( isotope.positionProperty.get().x ),
          this.modelViewTransform.modelToViewY( isotope.positionProperty.get().y ),
          this.modelViewTransform.modelToViewDeltaX( isotope.radius ), 0, 2 * Math.PI, true );
        context.fill();
      }

We decided that a 2 second delay on iPad2 is acceptable.

I wanted to offer a few suggestions in case we decide to proceed with this in the future:

  1. Move context.lineWidth = 0.4; outside the loop
  2. Transform the canvas itself once (before the loop starts), rather than doing modelToView 3x per iteration. May fail if the model view transform is extreme (>10^7 or <10^-7)

I suspect those would help a lot, another possibility is to try drawImage instead of beginPath/arc/fill (one image per each kind of particle).

Also tagging @aadish in case he is interested.