使用 fabricjs 添加形状作为背景
Add shape as background with fabricjs
我想使用 fabric.js 绘制一个形状作为背景。我试图在创建形状时将 scalable
设置为 false,但它没有按预期工作。
当 scalable
设置为 false 时,我无法 select 其他形状。有人可以告诉我该怎么做吗?
我使用的代码如下:
var pol = new fabric.Polygon([
{x: 200, y: 0},
{x: 250, y: 50},
{x: 250, y: 100},
{ x: 150, y: 100},
{x: 150, y: 50}
],
{
left: 0,
top: 0,
scaleX: 2,
scaleY: 2,
fill: 'green'
}
);
提前致谢。
您可以使用 setBackgroundImage
方法在 fabric.js 中将任何形状设置为背景。此方法不会影响其他形状,并且会解决对象选择问题。
ᴅᴇᴍᴏ
var canvas = new fabric.Canvas('c');
var pol = new fabric.Polygon([
{ x: 200, y: 0 },
{ x: 250, y: 50 },
{ x: 250, y: 100 },
{ x: 150, y: 100 },
{ x: 150, y: 50 }],
{
left: 0,
top: 0,
scaleX: 2,
scaleY: 2,
fill: 'green'
});
canvas.setBackgroundImage(pol);
canvas.renderAll();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
(function() {
var canvas = this.__canvas = new fabric.Canvas('canvas');
// create a rectangle with a fill and a different color stroke
var pol = new fabric.Polygon([
{x: 200, y: 0},
{x: 250, y: 50},
{x: 250, y: 100},
{ x: 150, y: 100},
{x: 150, y: 50}
],
{
left: 0,
top: 0,
selectable:false,
fill: 'green'
}
);
pol.set({
scaleX: canvas.width/pol.width,
scaleY: canvas.height/pol.height,
})
canvas.setBackgroundImage(pol);
canvas.renderAll();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>
这个适合任何 canvas 尺寸,设置 scaleX 和 scaleY
我想使用 fabric.js 绘制一个形状作为背景。我试图在创建形状时将 scalable
设置为 false,但它没有按预期工作。
当 scalable
设置为 false 时,我无法 select 其他形状。有人可以告诉我该怎么做吗?
我使用的代码如下:
var pol = new fabric.Polygon([
{x: 200, y: 0},
{x: 250, y: 50},
{x: 250, y: 100},
{ x: 150, y: 100},
{x: 150, y: 50}
],
{
left: 0,
top: 0,
scaleX: 2,
scaleY: 2,
fill: 'green'
}
);
提前致谢。
您可以使用 setBackgroundImage
方法在 fabric.js 中将任何形状设置为背景。此方法不会影响其他形状,并且会解决对象选择问题。
ᴅᴇᴍᴏ
var canvas = new fabric.Canvas('c');
var pol = new fabric.Polygon([
{ x: 200, y: 0 },
{ x: 250, y: 50 },
{ x: 250, y: 100 },
{ x: 150, y: 100 },
{ x: 150, y: 50 }],
{
left: 0,
top: 0,
scaleX: 2,
scaleY: 2,
fill: 'green'
});
canvas.setBackgroundImage(pol);
canvas.renderAll();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
(function() {
var canvas = this.__canvas = new fabric.Canvas('canvas');
// create a rectangle with a fill and a different color stroke
var pol = new fabric.Polygon([
{x: 200, y: 0},
{x: 250, y: 50},
{x: 250, y: 100},
{ x: 150, y: 100},
{x: 150, y: 50}
],
{
left: 0,
top: 0,
selectable:false,
fill: 'green'
}
);
pol.set({
scaleX: canvas.width/pol.width,
scaleY: canvas.height/pol.height,
})
canvas.setBackgroundImage(pol);
canvas.renderAll();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>
这个适合任何 canvas 尺寸,设置 scaleX 和 scaleY