如何根据父容器的高度和宽度缩放画布?

时间:2021-04-12 12:44:38

标签: html canvas vuetify.js fabricjs

我一直致力于使画布具有响应性,例如根据屏幕进行调整。

假设我有一个 1000 * 1000 的画布,我试图将画布缩小到父卡片/容器/div 的高度和宽度,并带有一点填充。 enter image description here

方法

1.基于 CSS 的方法 - 尝试过并且确实有效,但画布质量略有下降。

         .lower-canvas {
            width: 100% !important;
            height: 100% !important;
            position: relative !important;  
        }
        .upper-canvas {
            width: 100% !important;
            height: 100% !important;
            position: absolute !important;
        }
        .canvas-container {
            width: 100% !important;
            height: auto !important;
            border-radius: 20px;
        }  

代码笔: https://codepen.io/adatdeltax/pen/GRryXym

但这似乎不是正确的方法,并且画布对象在较小的情况下变得扭曲/模糊 屏幕。

2.Fabricjs 基于方法 - 当前在此方法中面临问题

我正在按照以下步骤解决问题。

  • 获取包装器 v-card 的高度和宽度。

  • 根据fabricjsmethods 缩放画布。

let canvas = this.canvas;
const outerCanvasContainer = document.getElementById('canvas-wrapper');
if (!outerCanvasContainer) return;
console.log(outerCanvasContainer, 'outerCanvasContainer');
const ratio = canvas.getWidth() / canvas.getHeight();
const containerWidth = outerCanvasContainer.clientWidth;
const scale = containerWidth / canvas.getWidth();
const zoom = canvas.getZoom() * scale;
canvas.setDimensions({
    width: containerWidth,
    height: containerWidth / ratio
});
canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0]);
canvas.renderAll();

目前在这种方法中面临一个问题,它不会缩放以适应容器,而是具有原始尺寸,即 1000*1000,不确定我哪里出错了,任何建议都会非常有帮助。

当前代码笔:** https://codepen.io/adatdeltax/pen/BapmqPX

0 个答案:

没有答案
相关问题