我有一个非常宽的图像,超过了大部分的查看宽度,必须使用 <canvas>
渲染标签。我如何 overflow hidden 并使图像居中?
换句话说,我正在寻找相当于 background-position: center
的 Canvas .
理想情况下,这将以一种响应式的方式完成 - 因此如果调整查看窗口的大小,图像将保持居中。
这是一个例子:
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("image");
ctx.drawImage(img, 0, 0);
};
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
}
canvas {
overflow: hidden;
}
.canvasContainer {
width: 100%;
overflow-x: hidden;
}
img {
display: none;
}
<div class="container">
<div class="canvasContainer">
<img id="image" src="http://via.placeholder.com/2400x800?text=center" />
<canvas id="canvas" width="2400" height="800" />
</div>
</div>
注意:有一个文本Center
出现在占位符中,但当前不可见
最佳答案
这段代码应该可以满足您的需要。 图像宽度应设置为 canvas.width 以避免图像溢出 Canvas 。 图像高度现在是相对于图像宽度的,所以比例保持不变。 我包含了一个事件监听器,它会将您的 Canvas /图像调整为窗口的大小。
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("image");
var canHeight = window.innerWidth / 4;
canvas.width = window.innerWidth;
canvas.height = canHeight;
var width = canvas.width;
ctx.drawImage(img, 0, 0, width, canHeight);
}
init();
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
init();
});
关于html - Canvas 图像 : center wide image and hide overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052186/