Here's the code.
Happily, we're already storing the hero x & y position in local variables before we apply the movement (to know whether to animate the legs or not), so after the move we have a really easy way to "undo" the move.
function handle_keys_that_are_pressed() {
var prev_x = hero.x;
var prev_y = hero.y;
if (keys[37]) { // Left
hero.x -= hero_speed;
}
if (keys[39]) { // Right
hero.x += hero_speed;
}
if (keys[38]) { // Up
hero.y -= hero_speed;
}
if (keys[40]) { // Down
hero.y += hero_speed;
}
if (is_touching_an_obstacle(hero)) {
hero.x = prev_x; // moved into an obstacle so undo the move
hero.y = prev_y;
}
if (hero.x == prev_x && hero.y == prev_y) hero.animation_rate= 0 // not moving
else hero.animation_rate= 2; // wriggling legs
}