Move var dx, newwidth outside of their forloop.