最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resize background image of canvas - Fabricjs - Stack Overflow

programmeradmin1浏览0评论

I am using fabricjs to play around with canvas, and loading a image into it via javascript.

I have a function that resizes the canvas to make it responsive and as such would like to resize the background image that was loaded to fit the canvas too but keep the aspect ratio.

I have not found examples currently that meet my criteria and am hoping someone can assist.

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);

I am using fabricjs to play around with canvas, and loading a image into it via javascript.

I have a function that resizes the canvas to make it responsive and as such would like to resize the background image that was loaded to fit the canvas too but keep the aspect ratio.

I have not found examples currently that meet my criteria and am hoping someone can assist.

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);
Share Improve this question asked Apr 30, 2016 at 7:01 AeseirAeseir 8,43412 gold badges62 silver badges125 bronze badges 3
  • can i have jsfiddle for this ? – Sagar R Commented Apr 30, 2016 at 7:03
  • Aeseir, I am facing same issue. Di you find the solution for it? – Haresh Godhani Commented Jul 23, 2018 at 14:20
  • yea, just posted the answer – Aeseir Commented Jul 23, 2018 at 23:43
Add a ment  | 

3 Answers 3

Reset to default 5

Your resizeCanvas() should look like:

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

And you should be ok.

In order to set background image by preserving the aspect ratio of the image and also set it in the center of the canvas.

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;

};

My solution in 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)

  1. 暂无评论