javascript - 2 Canvas 使用 drawImage 将一个 Canvas 置于另一个 Canvas 的中心

标签 javascript css html canvas html5-video

我正在尝试将 Canvas 置于另一个 Canvas 的中心并将其居中。我希望它能够响应,事实证明这比我想象的要难。

我有这个结构。

 <div class="photobooth"> // container
<div class="controls">    // just for the CTA btn
  <button class="cta" onClick="takePhoto()">Take Photo of your ID front please. Place the document  within the red border</button>
  <canvas class="blurPhoto" ></canvas> // the big canvas

//小 Canvas ,用户应该将文档放在 Canvas 的边界内 //隐藏,这是获取 Canvas 数据所必需的

<div class="strip">This goes to the database</div>

我想要的是应用了模糊的全屏背景。在那个模糊的 Canvas 的中心(或者它可以是视频元素,也许对视频元素应用模糊并将 Canvas 居中会更好?),我想要一个清晰的 Canvas 显示准实时的数据馈送在视频元素上。

内部 Canvas 的模糊背景和红色边框向用户指示文档的放置位置(整个应用程序是 Revolut KYC UI 的原始模拟器)。

现在我不确定什么是最好的,用 CSS 或 JS 设置所有这些。

video {
position:absolute;
top:0px;
z-index:-1;
width:10%;
height:10%;
filter :blur(1px);
display:none;
}

这里我隐藏了视频,设置多少百分比的高度和宽度似乎并不重要,Canvas 上的 JS 无论如何都会覆盖它。

因为我不能嵌套 Canvas ,在这里我不知道还能做什么..

.photo { // this is the small canvas which should be centered within the big one
 position:absolute;

 width:50vw;
 height:50vh;

 border:1px red solid;


}

.blurPhoto { big canvas
 position:relative;
 width:100vw;
 height:100vh;
 filter :blur(10px);
  border:1px red solid;

 }

现在,由于 .photo canvas 父元素是包装器 div,设置位置 top:100% 不符合我的要求,因此我已将其删除。

这里我缓存了 2 个 Canvas :

const canvas = document.querySelector('.photo');
const ctx = canvas.getContext('2d');
const canvasBig = document.querySelector('.blurPhoto');
const ctx2 = canvasBig.getContext('2d');

这是相关的 JS 函数:

function paintToCanvas() {
const width = video.videoWidth;
const height = video.videoHeight;
canvas.width = width;
canvas.height = height;


return setInterval(() => {


 ctx.drawImage(video, 0,
    0, width, height);

 ctx2.drawImage(video, 0,
    0, width, height);  // this is overruled by the CSS set on it


 }, 16);
  }

那么,我该如何让它发挥作用。 我应该简单地使用视频元素作为背景吗? 是否有可能具有这种响应性?

这是 codepen 链接,我已经更改了一些 CSS,但仍然不满意。

https://codepen.io/damPop/pen/GwqxvM

最佳答案

取自https://css-tricks.com/centering-css-complete-guide/

将两个 Canvas 放在容器 div 中并使用 % 技巧居中

.container {
    position: relative;
}
.photo   {
    position: absolute;
    width:50vw;
    height:50vh;
    border:1px red solid;

    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.blurPhoto { big canvas
    position:absolute;
    top: 0;
    left: 0;
    width:100vw;
    height:100vh;
    filter :blur(10px);
    border:1px red solid;
 }

关于javascript - 2 Canvas 使用 drawImage 将一个 Canvas 置于另一个 Canvas 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552880/

相关文章:

javascript - livesearchgridpanel 上的分页工具栏出现问题

javascript - 给定属性的值,如何找到它的字符串值

html - CSS3 : Flex display and overflow

html - 为什么不显示背景图像?

php - 我将index.html 更改为index.php,但现在页面无法加载!

javascript - 如何在 JavaScript 中换行?

javascript - 如何在node.js中允许http?

javascript - JQuery 动画到基于 vw 的位置

javascript - 在angularjs的聊天框中滚动到底部

html - 修复 Canvas 外的侧边栏