如何在Fabric.js中动态缩放对象到画布大小

时间:2013-09-23 08:19:28

标签: javascript css canvas svg fabricjs

我希望增加svg图像的高度和宽度,与画布的高度和宽度相同,使其看起来像画布的背景图像。当我按下“设置背景”按钮时,一个svg图像将从我的目录设置为画布。我想动态地将此图像缩放到画布高度和宽度。

预期输出:I want this

HTML

<h1>canvas</h1>
<canvas style="left: -300px; border: 1px dotted;" height="385" width="400" id="c"></canvas>
<input type="button" id="svg3" value="set background" />

脚本

$(document).ready(function(){
    var canvas = new fabric.Canvas('c');
    var colorSet="red";
    $("#svg3").click(function(){
        fabric.loadSVGFromURL('http://upload.wikimedia.org/wikipedia/en/c/cd/-Islandshreyfingin.svg', function (objects, options) { 
            var shape = fabric.util.groupSVGElements(objects, options);
            shape.set({
                left: 150,
                top:200,
                //height: 700,
                //width: 700,
                scaleX: .35,
                scaleY:.35
            });

            if (shape.isSameColor && shape.isSameColor() || !shape.paths) {
                shape.setFill(colorSet);
            } else if (shape.paths) {
                for (var i = 0; i < shape.paths.length; i++) {
                    shape.paths[i].setFill(colorSet);
                }
            }

            canvas.add(shape);
            canvas.renderAll();
        });
    });
});

这是我的FIDDLE Demo

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:20)

你知道你的画布宽度和高度。所以this会起作用:

shape.set({
    top: canvas.height/2,
    left: canvas.width/2,
    scaleY: canvas.height / shape.height,
    scaleX: canvas.width / shape.width
});

答案 1 :(得分:2)

我终于得到了解决方案:

HTML

<h1>canvas</h1>
<canvas style="left: -300px; border: 1px dotted;" height="585" width="400" id="c"></canvas>
<input type="button" id="svg3" value="set background" />
<input type="button" id="color" value="Change Image Color" />

的JavaScript

function setBackgroundColor(color) {
    if (background.isSameColor && background.isSameColor() || !background.paths) {
        background.setFill(color);
    } else if (background.paths) {
        for (var i = 0; i < background.paths.length; i++) {
            background.paths[i].setFill(color);
        }
    }
}

var canvas = new fabric.Canvas('c');
var background;


$("#svg3").click(function() {
    fabric.loadSVGFromURL('http://upload.wikimedia.org/wikipedia/en/c/cd/-Islandshreyfingin.svg', 
        function (objects, options) { 
            background = fabric.util.groupSVGElements(objects, options);


            background.set({
                left: canvas.width/2,
                top: canvas.height/2,
                scaleY: canvas.height / background.width,
                scaleX: canvas.width / background.width,
                 selectable: false
            });

            setBackgroundColor('red');

            canvas.add(background);
            canvas.renderAll();
        });
});

$("#color").click(function(){
    setBackgroundColor('blue');
    canvas.renderAll();
});

工作演示Fidddle