如何在缩放画布时保持相同的放大镜圆半径

时间:2016-05-18 06:41:07

标签: javascript canvas fabricjs

我正在尝试在 fabric.js 中实现一项功能,我必须使用放大镜和鼠标滚动来缩放图像。我几乎已经实现了它,唯一的问题是在缩放画布时(通过鼠标滚动),放大镜圆圈也会缩放。

(function () {
    var canvas = this.__canvas = new fabric.Canvas('c');

    var radius = 100,
        x = 300,
        y = 300,
        lens,
        scale = 2,
        originalWidth = 600,
        originalHeight = 600;

    fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function (img) {
        img.set({
            width: originalWidth,
            height: originalHeight,
            evented: true,
            selectable: false
        });

        lens = fabric.util.object.clone(img);
        lens.set({
            width: scale * originalWidth,
            height: scale * originalHeight,
            clipTo: function (ctx) {
                ctx.arc(-this.left + x - this.width / 2, -this.top + y - this.height / 2, radius, 0, Math.PI * 2, true);
            }
        });

        canvas.add(img, lens);
    });

    canvas.on('mouse:move', function (e) {
        x = e.e.layerX;
        y = e.e.layerY;
        lens.set('left', -(scale - 1) * x);
        lens.set('top', -(scale - 1) * y);
        canvas.renderAll();
    });


var canvasarea = document.getElementById("canvases");
canvasarea.addEventListener("mousewheel", _zoomCanvas, false);
/// Firefox
canvasarea.addEventListener("DOMMouseScroll", _zoomCanvas, false);


function _zoomCanvas(e, dragDelta, isDragged) {  
		var evt=window.event || e;
		var delta = (dragDelta == undefined) ? evt.detail? evt.detail*(-120) : evt.wheelDelta : dragDelta;

		var curZoom = canvas.getZoom(),  newZoom = curZoom + delta / 4000,
		x = e.offsetX, y = e.offsetY;

		if(newZoom < 0 || newZoom < canvas.scaleX) return;				 
		///applying zoom values.
		canvas.zoomToPoint({ x: x, y: y }, newZoom);
	
	if(e != null)e.preventDefault();
	return false;
} 




})();
canvas{
  border-width: 1pz;
  border-style: solid;
  border-color: #000;
}
<script src="http://fabricjs.com/build/files/text,gestures,easing,parser,freedrawing,interaction,serialization,image_filters,gradient,pattern,shadow,node.min.js"></script>
<div id="canvases">
<canvas id="c" width="600" height="600"></canvas>
</div>

jsFiddle:https://jsfiddle.net/ankur02/kvht1637/

0 个答案:

没有答案