var ctx = document.getElementById('image-viewer').getContext('2d');
var images = [
'http://i.imgur.com/5PF0Xdi.jpg',
'http://i.imgur.com/po0fJFT.png',
'http://i.imgur.com/Ijzdt0o.png'
];
var counter = 0;
setInterval(function() {
loadScaleAndCenterImage(ctx, images[counter++ % images.length]);
}, 2000);
function loadScaleAndCenterImage(ctx, url) {
var imageObj = new Image();
imageObj.onload = function(e) {
var ctxWidth = ctx.canvas.width,
ctxHeight = ctx.canvas.height;
var imgWidth = imageObj.width,
imgHeight = imageObj.height;
var ratioWidth = imgWidth / ctxWidth,
ratioHeight = imgHeight / ctxHeight,
ratioAspect = ratioWidth > 1 ? ratioWidth : ratioHeight > 1 ? ratioHeight : 1;
var newWidth = imgWidth / ratioAspect,
newHeight = imgHeight / ratioAspect;
var offsetX = (ctxWidth / 2) - (newWidth / 2),
offsetY = (ctxHeight / 2) - (newHeight / 2);
ctx.clearRect(0, 0, ctxWidth, ctxHeight);
ctx.drawImage(this, offsetX, offsetY, newWidth, newHeight);
};
imageObj.src = url;
}
#image-viewer {
background-color: #E4E4E4;
background-image:
linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F),
linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F);
background-size: 20px 20px;
background-position: 0 0, 30px 30px
}
<canvas id="image-viewer" width="1280" height="960"></canvas>