I am trying to load a HTML file that does one thing: display an image on a canvas element that is auto-resized and auto-rescaled to the maximum dimensions for the device in question.
For example:
- User presses button on device.
- Device opens WebKit/WebView to http://some.url/page.html.
- That page shows image.png in the maximum height/width proportion possible on said device.
Requirements:
- Actual HTML file should only contain a canvas element within the body.
- Image path should be dynamic and the width/height interpreted after the file has been loaded.
- No third party dependencies.
I took a stab at this here, but am running into problems: http://jsfiddle.net/zfG2B/
if (scaledHeight < scaledWidth) {
_config.newImgHeight = _cache.canvas.height;
_config.newImgWidth = Math.round(_config.newImgHeight * _config.imgWidthRatio);
} else if (scaledWidth < scaledHeight) {
_config.newImgWidth = _cache.canvas.width;
_config.newImgHeight = Math.round(_config.newImgWidth * _config.imgHeightRatio);
}
The code I've cobbled together (above, and see jsfiddle) kind of works, but I can only get it to rescale based on the height. Any ideas on what I've done wrong or the best path forward?
For reference, I've attempted to join together the best of:
- HTML5 Canvas Resize (Downscale) Image High Quality?
- Scaling HTML5 canvas width preserving w/h aspect ratio
- Resizing an image in an HTML5 canvas
- HTML5 Canvas drawImage ratio bug iOS
- scaling a canvas element and keeping the aspect ratio
So here's the question: what's the best way to place an Image on a Canvas in HTML5 and make it auto-rescale based on the current screen size? Bonus points for being able to specify a clipping range!