Fabric JS-在画布上重绘对象以调整大小

时间:2019-02-12 13:50:17

标签: javascript fabricjs responsive

我有一个带有背景图像的画布,在此图像上,我可以绘制多边形和矩形。 调整窗口大小时,可以调整图像大小,但是找不到在画布中调整对象大小的方法。

缩放对象注释之后,无法正常工作。

PS:对于对象缩放,我只是在这里使用示例-> Scale fabric.js canvas objects

这是我的代码:

function renderCanvas(canvas, base64Image) {
var img = new Image();
img.src = base64Image.src;    
img.onload = function() {
    var f_img = new fabric.Image(img);
    var canvas_parent_size = $('.canvas-wrapper').width();
    var canvas_width = Math.min(f_img.width,canvas_parent_size);
    var scale = canvas_width / f_img.width;
    var canvas_height = f_img.height * scale;
    canvas.setBackgroundImage(f_img, canvas.renderAll.bind(canvas), {

            top: 0,
            left: 0,
            scaleX: scale,
            scaleY: scale
        });
    canvas.setWidth(canvas_width);
    canvas.setHeight(canvas_height); 

    //json
    var polygonDataField = JSON.parse(document.querySelector('input.input-polygonData').value);  

    console.log(polygonDataField);

    //scale objects        
    var factor = canvas_width/polygonDataField.backgroundImage.width;
    var objects = canvas.getObjects();
    objects.forEach( obj => {

        var scaleX = obj.scaleX;
        var scaleY = obj.scaleY;
        var left = obj.left;
        var top = obj.top;

        var tempScaleX = scaleX * factor;
        var tempScaleY = scaleY * factor;
        var tempLeft = left * factor;
        var tempTop = top * factor;


        obj.scaleX = tempScaleX;
        obj.scaleY = tempScaleY;
        obj.left = tempLeft;
        obj.top = tempTop;

        obj.setCoords();
    });

    canvas.renderAll();
    canvas.calcOffset();

};

0 个答案:

没有答案