调整画布背景图像大小 - Fabricjs

4

我正在使用fabricjs操纵画布,并通过JavaScript加载图像。

我有一个函数,用于调整画布大小以使其响应式,并希望调整已加载的背景图像以适合画布,但保持长宽比。

目前我还没有找到符合我的要求的示例,希望有人能提供帮助。

Javascript

var canvas = new fabric.Canvas('drawing_layer');
 var img = new Image();
            img.onload = function () {
                canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
                    originX: 'left',
                    originY: 'top',
                    left: 0,
                    top: 0
                });

// initially sets width of canvas to fit the image
                canvas.setDimensions({
                    width: img.width,
                    height: img.height
                });
            };
// below is a call to function that resizes the canvas
resizeCanvas();

//sets listener to resize event
            window.addEventListener('resize', resizeCanvas);

我可以为此使用JSFiddle吗? - Sagar R
Aeseir,我也遇到了同样的问题。你找到解决方案了吗? - Haresh Godhani
是的,刚刚发布了答案。 - Aeseir
3个回答

5
您的resizeCanvas()函数应该长这样:
resizeCanvas(width, height) {
  canvas.backgroundImage.scaleToWidth(width);
  canvas.backgroundImage.scaleToHeight(height);
  canvas.setDimensions({width: width, height: height});
  canvas.renderAll();
}

你应该没问题了。


0
为了在画布中保持图像的纵横比并将其置于中心位置,需要设置背景图像。
const setBackgroundFromDataUrl = (dataUrl, options = {}) => {
  if (!dataUrl) { return true; }

  let img = new Image();
  img.setAttribute('crossOrigin', 'anonymous');
  img.onload = () => {

   // maxWidth // Max width of the canvas
   // maxHeight //Max height of canvas

    let imgWidth = img.width; // Current image width
    let imgHeight = img.height; // Current image height

    let widthAspectRatio = maxWidth / imgWidth;
    let heightAspectRatio = maxHeight / imgHeight;

    let finalAspectRatio = Math.min(widthAspectRatio, heightAspectRatio)

    let finalHeight = imgHeight * finalAspectRatio;
    let finalWidth = imgWidth * finalAspectRatio;

    let imgTop = 0;
    if (maxHeight > finalHeight) {
      imgTop = (Math.round(maxHeight) - Math.round(finalHeight)) / 2;
    }

    let imgLeft = 0;
    if (maxWidth > finalWidth) {
      imgLeft = (Math.round(maxWidth) - Math.round(finalWidth)) / 2;
    }

    let nsgImage = new fabric.Image(img).scale(finalAspectRatio);
    nsgImage.set({ left: imgLeft, top: imgTop });

    canvas.setBackgroundImage(nsgImage, () => canvas.renderAll());

  }

  img.src = dataUrl;

};

-1

我的Angular 2+解决方案。

@HostListener('window:resize', ['$event'])
      resizeCanvas(event?: any) {
        const width: number = (window.innerWidth > 0) ? window.innerWidth : screen.width;
        const height: number = (window.innerHeight > 0) ? window.innerHeight : screen.height;
        const widthn: number = width * 0.7;
        const heightn: number = height - 100;
        canvas.setDimensions({
          width: widthn,
          height: heightn,
        });
      }

0.7和100代表什么? - Dusan Radovanovic
在整体上看,宽度会缩小到大小的70%,而高度会减少100像素。 - Aeseir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接