簡體   English   中英

如何調整背景圖片的大小以匹配畫布? FabricJS

[英]How to resize a background image to match the canvas? FabricJS

所以我目前有一個問題。 我正在使用Meteor.js和Fabric.js,並且試圖找出如何重新縮放圖像以適合畫布。 目前,這是我的代碼:

 var canvas = new fabric.Canvas('c1');
 canvas.setWidth(800);
 canvas.setHeight(800);
 var canvasHeight = canvas.height;
 var canvasWidth = canvas.width;

 //Just a debug statement console.log(canvasWidth, canvasHeight);

 var bgImg = new fabric.Image();
 bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-
 Traffic.jpg');
 bgImg.set({
    top: canvasHeight / 2,
    left: canvasWidth / 2,
    scaleX: canvasWidth/bgImg.width,
    scaleY: canvasHeight/bgImg.height,
 });

 canvas.setBackgroundImage(bgImg);

這樣的結果是我得到的圖像片段未按比例縮放到正確的大小。 想知道我缺少什么?

(已經檢查了其他答案,但是無法將其應用於流星,JS初學者)

由於.setSrc異步加載圖像,因此需要等待圖像完成加載后才能知道其尺寸

.setSrc有一個可選的回調參數,當圖像完成加載時調用該參數,因此您可以執行

var bgImg = new fabric.Image();
bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-Traffic.jpg', function() {
    bgImg.set({
        top: canvasHeight / 2,
        left: canvasWidth / 2,
        scaleX: canvasWidth/bgImg.width,
        scaleY: canvasHeight/bgImg.height,
    });
    canvas.setBackgroundImage(bgImg);
});

setSrc是異步的。 您可以提供一個函數作為在圖像加載后運行的回調:

變種

canvas = new fabric.Canvas('c1');
canvas.setWidth(800);
canvas.setHeight(800);
var canvasHeight = canvas.height;
var canvasWidth = canvas.width;

//Just a debug statement console.log(canvasWidth, canvasHeight);

var bgImg = new fabric.Image();
bgImg.setSrc('http://www.aamcocolorado.com/images/Highway-Traffic.jpg', function () {
  bgImg.set({
    top: 0,
    left: 0,
    scaleX: canvasWidth/bgImg.width,
    scaleY: canvasHeight/bgImg.height,
  });
});

canvas.setBackgroundImage(bgImg);

https://jsfiddle.net/upg0tyvz/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM