画布边框颜色随着画布对象的变化而变化

时间:2015-05-11 12:51:16

标签: canvas fabricjs

我正在尝试在画布上使用边框打印设计,如果画布对象缩放或调整到超出边框,画布边框颜色应更改为红色或显示一些消息。

如果画布对象触摸或穿过画布的边框,则如何更改边框颜色。

2 个答案:

答案 0 :(得分:1)

我知道这已经过时了,但我恰好正在研究同样的问题(只是改变颜色)这就是我所做的,希望它会帮助其他人解决同样的问题

http://jsfiddle.net/Lfqdj5hu/1/

由于某种原因小提琴wasent使用jquery所以这是一个快速尝试

var canvas = new fabric.Canvas('demo');



canvas.setWidth(600);
canvas.setHeight(500);

canvas.on({
      'object:moving':boundingBox,
      'object:scaling':boundingBox,
      'object:rotating':boundingBox,
    });

function boundingBox(bbox){
    // detecting sides of the canvas
    if(bbox.target.getWidth() + bbox.target.left > canvas.width
       || bbox.target.getHeight() + bbox.target.top > canvas.height 
       || bbox.target.top < 0 
       || bbox.target.left < 0){
        //$('#demo').css('box-shadow', '0 0 20px red');
        var cd = document.getElementById('demo');
        var cdStyle = cd.style;
        cdStyle.backgroundColor = 'red';
    } else {
        //$('#demo').css('box-shadow'. '0 0 20px #a8a8a8');
        var cd = document.getElementById('demo');
        var cdStyle = cd.style;
        cdStyle.backgroundColor = 'white';
    }
}



var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'blue',
  width: 50,
  height: 50
});

var circle = new fabric.Circle({
  radius: 95, 
  fill: 'green', 
  left: 175, 
  top: 200
});

canvas.add(rect);
canvas.add(circle);

我希望有人发现这个有用的

答案 1 :(得分:0)

在官方网站上查看此示例:http://fabricjs.com/intersection/ - 可以使用intersectsWithObject()函数检测到冲突。

对于你的问题,请检查这个小提琴:http://jsfiddle.net/FD53A/54/

canvas.on('object:moving', function (e) {
    var obj = e.target;
    obj.setCoords();

    canvas.forEachObject(function (targ) {
        activeObject = canvas.getActiveObject();

        if (targ === activeObject) return;


        if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
            activeObject.left = targ.left - activeObject.currentWidth;
        }
        if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
            activeObject.left = targ.left + targ.currentWidth;
        }
        if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
            activeObject.top = targ.top - activeObject.currentHeight;
        }
        if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
            activeObject.top = targ.top + targ.currentHeight;
        }
        if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {
            targ.strokeWidth = 10;
            targ.stroke = 'red';
        } else {
            targ.strokeWidth = 0;
            targ.stroke = false;
        }
        if (!activeObject.intersectsWithObject(targ)) {
            activeObject.strokeWidth = 0;
            activeObject.stroke = false;
        }
    });
});