I think this patch may not need to calculate by this. You may replace the order of variable to have the correct x, y, w, h and just use it in drawImage. Like (I haven't tested it, and I will test it tomorrow. If I am wrong, please tell me.):

```
    var scale = Math.min(tw / vw, th / vh);
    var w = vw * scale, h = vh * scale;
    var x = (tw - w) / 2, y = (th - h) / 2;
```