问题描述
我正在尝试将事件绑定到背景图片:
I'm trying to bind an event to a background image:
var imgInstance = fabric.Image.fromURL(path, function(oImg) {
oImg.on("selected", function() {
alert();
});
canvas.setBackgroundImage(oImg, canvas.renderAll.bind(canvas), {
top: 0,
left: 0
});
oImg.on("selected", function() {
alert();
});
});
我可以使它工作.我正在尝试绑定鼠标事件以处理拖动,因此可以在图像大于画布时移动图像,例如background-cover css属性.
I can get it work. I'm trying to bind mouse events to handle drag, so i can move the image when it's bigger than the canvas, like background-cover css property.
有想法吗?
谢谢大家!
解决方案:
var DragStart = false;
canvas.on('mouse:down', function(options) {
if (!options.target) {
DragStart = true;
}else {
DragStart = false;
}
});
canvas.on('mouse:move', function(options) {
if (DragStart) {
var bounds = getBounds(options.e); // validate boundaries between image and canvas
canvas.backgroundImage.top = bounds.y;
canvas.backgroundImage.left = bounds.x;
canvas.renderAll();
}
});
推荐答案
似乎无法将事件添加到背景图像中……但是画布确实会发出事件,并且如果您单击画布并且没有目标是设置,那么他们必须单击背景.背景图像不会被强制占用整个背景,但是我不确定为什么不占用整个背景.
It doesn't seem like you can add events to the background image... but the canvas does emit events and if you click the canvas and no target is set then they must be clicking the background. Background image are not forced to take up the whole background but I'm not sure reasons to not make it take up the whole background.
尽管您确实传递了鼠标事件,所以如果背景图像不占用整个背景,则可以进行数学运算并弄清楚它们单击的位置.
You do get the mouse event passed in though so if the background image does not take up the whole background you could do that math and figure out where they clicked.
window.canvas = new fabric.Canvas('c', { selection: false, preserveObjectStacking:true });
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(o) {
canvas.setBackgroundImage(o, canvas.renderAll.bind(canvas), {
top: 0,
left: 0
});
});
canvas.on('mouse:down', function(options) {
if (!options.target) {
console.log('target is null')
}
});
canvas.add(new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#faa',
originX: 'left',
originY: 'top',
centeredRotation: true
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<canvas id="c" width="600" height="600"></canvas>
这篇关于fabric.js:将事件绑定到背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!