gpt4 book ai didi

javascript - 如何相对于视口(viewport)调整 Canvas 图像

转载 作者:行者123 更新时间:2023-11-28 06:36:28 25 4
gpt4 key购买 nike

我正在尝试使 Canvas 图层图像响应 Canvas 背景图像,两者都显示出良好的响应行为,但我的问题是我想将图层图像固定在屏幕中央,无论屏幕大小是多少。目前在调整我的图层图像大小时开始改变其不受欢迎的位置。我想将图层图像固定在屏幕中央

这是我的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 规则使图层在视口(viewport)中居中:

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

demo

关于javascript - 如何相对于视口(viewport)调整 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34648022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com