A major challenge in atomic force microscopy is to reduce the scan duration while retaining the image quality. Conventionally, the scan rate is restricted to a sufficiently small value in order to ensure a desirable image quality as well as a safe tip–sample contact force. This usually results in a conservative scan rate for samples that have a large variation in aspect ratio and/or for scan patterns that have a varying linear velocity. In this paper, an adaptive scan scheme is proposed to alleviate this problem. A scan line-based performance metric balancing both imaging speed and accuracy is proposed, and the scan rate is adapted such that the metric is optimized online in the presence of aspect ratio and/or linear velocity variations. The online optimization is achieved using an extremum-seeking approach, and a semiglobal practical asymptotic stability result is shown for the overall system. Finally, the proposed scheme is demonstrated via both simulation and experiment.