html - Canvas 图像 : center wide image and hide overflow

标签 html css canvas responsive centering

我有一个非常宽的图像,超过了大部分的查看宽度,必须使用 <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/

相关文章:

css - 如何在不弄乱的情况下修改此页面剥离效果?

java - 使用 Canvas 和位图的全屏图像

javascript - 我的 Javascript 游戏的坐标 - 基于 Angular ,我什么时候使用 Sin Cos 和 Tan?

javascript - 如何将变量分配给输入元素中的值属性?

html - 使 box-shadow 比元素本身更宽

jquery - 获取 Bootstrap 元素在较小屏幕上的高度

javascript - 调整 Canvas 大小而不裁剪

jquery - 固定容器中的随机移动

html - 子div没有得到父div的原始高度,为什么?

javascript - 让 html 元素保持在相同位置而不使用位置 : fixed