I found a solution, that fits my needs:
If the centre of the circle is at right angles to one of the sides of the rectangle, the distance is simply the distance between the centre of the circle to that side minus the radius of the circle.
Otherwise, I take the nearest corner of the rectangle to the centre of the circle and calculate the distance using the Pythagorean theorem. Here you also have to subtract the radius of the circle.
Note: This code doesn't check if the circle is inside the rectangle, or vice versa.
function getDistanceCircleRect(circle, rectangle){ // x and y are the centre coordinates xC = circle.x; yC = circle.y; r = circle.width/2; xR = rectangle.x; yR = rectangle.y; wR = rectangle.width; hR = rectangle.height; topR = yR - hR/2; bottomR = yR + hR/2; leftR = xR - wR/2; rightR = xR + wR/2; if(yC >= topR && yC <= bottomR && ((xC+r) >= rightR || (xC-r) <= leftR)){ d1 = Math.abs(xC - rightR); d2 = Math.abs(xC - leftR); min_distance = Math.min(d1, d2) - r; } else if(xC >= leftR && xC <= rightR && ((yC+r) >= bottomR || (yC-r) <= topR)){ d1 = Math.abs(yC - topR); d2 = Math.abs(yC - bottomR); min_distance = Math.min(d1, d2) - r; } else{ nextX = Math.min(Math.abs(xC - leftR), Math.abs(xC - rightR)); nextY = Math.min(Math.abs(yC - topR), Math.abs(yC - bottomR)); min_distance = Math.sqrt((nextX)**2 + (nextY)**2) - r; } return min_distance; }