< Retour
JS background-size: cover
DOM
function resizeToCover(el, imageWidth, imageHeight, sceneWidth, sceneHeight) {
if (imageWidth/imageHeight < sceneWidth/sceneHeight) {
el.style.width = sceneWidth + 'px';
var newHeight = imageHeight*(sceneWidth/imageWidth);
el.style.height = newHeight + 'px';
el.style.top = -((newHeight - sceneHeight) / 2) + "px";
el.style.left = 0;
}
else {
el.style.height = sceneHeight + 'px';
var newWidth = imageWidth*(sceneHeight/imageHeight);
el.style.width = newWidth + 'px';
el.style.top = 0;
el.style.left = -((newWidth - sceneWidth) / 2) + "px";
}
}
Canvas
function drawCoverImage(ctx, img, w, h) {
var image_w = img.width,
image_h = img.height,
scene_w = w,
scene_h = h;
if (scene_w <= scene_h) {
var drawn_w = image_w*(scene_h/image_h),
x_offset = ((drawn_w - scene_w) / 2)* -1;
ctx.drawImage(img, x_offset, 0, drawn_w, scene_h);
} else {
var drawn_h = image_h*(scene_w/image_w),
y_offset = ((drawn_h - scene_h) / 2)* -1;
ctx.drawImage(img, 0, y_offset, scene_w, drawn_h);
}
}