调整画布的背景图像 - Fabricjs

时间:2016-04-30 07:01:29

标签: javascript canvas fabricjs

我正在使用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);

3 个答案:

答案 0 :(得分:1)

你的resizeCanvas()应如下所示:

resizeCanvas(width, height) {
  canvas.backgroundImage.scaleToWidth(width);
  canvas.backgroundImage.scaleToHeight(height);
  canvas.setDimensions({width: width, height: height});
  canvas.renderAll();
}

你应该没事。

答案 1 :(得分:0)

我在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,
        });
      }

答案 2 :(得分: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;

};