如何相对于视口调整画布图像

How to adjust canvas images relative to viewport

本文关键字:图像 布图像 相对于 视口 调整      更新时间:2023-09-26

我正在尝试使画布层图像响应画布背景图像,两者都显示出良好的响应行为,但我的问题是,我想修复屏幕中心的层图像,无论屏幕大小如何。目前在重新调整我的图层图像的大小时,开始改变它的位置,这是不可取的。我想把图层图像固定在屏幕中央

这是我的html代码

<body id="body">
    <canvas id="myCanvas" style="position:relative;"></canvas>

    <img src="background.jpg" id="background" />
    <img src="s01.jpg" id="layer" />

这是我的css

#layer {
    position: fixed;
    top: 0px;
    margin-left: -160px;
}
img{
        width:auto;
        height:auto;
        max-width:100%;
        max-height:100%;
    }
body {
        /*background: #E9E9E9;*/
        color: #333;
        font: 1em/1.3em "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif;
        text-shadow: rgba(255,255,255,0.8) 0 1px 0;
        text-align: center;
        overflow:hidden;
    }
    html, body {
        width:100%;
        height:100%;
        margin:0;
    }

这是我的js

(function() {
    var
        htmlCanvas = document.getElementById('myCanvas'),
        context = htmlCanvas.getContext('2d');
    var background = document.getElementById('background');
    context.drawImage(background, 0, 0, window.innerWidth, window.innerHeight);
    initialize();
    function initialize() {
        window.addEventListener('resize', resizeCanvas, false);
        resizeCanvas();
    }
    function redraw() {
        context.strokeStyle = 'transparent';
        context.lineWidth = '5';
        context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
        var background = document.getElementById('background');
        context.drawImage(background, 0, 0, window.innerWidth, window.innerHeight);
        var imageObj = new Image();
        imageObj.onload = function() {
            context.drawImage(imageObj, 0, 0, window.innerWidth, window.innerHeight);
        };
        imageObj.src = 'background.jpg';
    }
    function resizeCanvas() {
        htmlCanvas.width = window.innerWidth;
        htmlCanvas.height = window.innerHeight;
        redraw();
    }
})();

我在这里被困了三天,仍然无法弄清楚

我在您的脚本中找不到任何问题。它写得很好。但是你只需要应用这个css规则来在视口中居中图层:

#layer {
    position: fixed;
    top: 0px;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

演示