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;
// Load a new image after 2 seconds.
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>
准确预期但它使图像失去它的比例:[链接](http://stackoverflow.com/a/14731922/4762384) –
欢迎来到SO。请访问[帮助],看看有什么和如何问。提示:在[mcve] – mplungjan
中发布努力和代码感谢提醒 –