gpt4 book ai didi

javascript - Fabric .js : bind event to background image

转载 作者:太空宇宙 更新时间:2023-11-04 16:29:55 25 4
gpt4 key购买 nike

我正在尝试将事件绑定(bind)到背景图像:

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();
});
});

我可以让它工作。我正在尝试绑定(bind)鼠标事件来处理拖动,这样当图像大于 Canvas 时我就可以移动图像,例如背景覆盖 CSS 属性。

想法?

谢谢大家!

解决方案:

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();
}
});

最佳答案

您似乎无法将事件添加到背景图像...但 Canvas 确实会发出事件,如果您单击 Canvas 并且未设置目标,那么它们一定是单击背景。背景图像不会被迫占据整个背景,但我不确定不让它占据整个背景的原因。

您确实获得了传入的鼠标事件,因此如果背景图像没有占据整个背景,您可以进行数学计算并找出他们单击的位置。

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>

关于javascript - Fabric .js : bind event to background image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com