【问题标题】:how to fix the position of mask in snapsvg.js?如何修复 snapsvg.js 中遮罩的位置?
【发布时间】:2026-02-02 09:45:01
【问题描述】:

这里是js代码:

var cv = Snap('#cv').attr({height: '100%', width: '100%'});

var mskHide = cv.rect().attr({height: '100%', width: '100%', left:0, top:0, fill: '#666'});
var mskShow = cv.circle(200, 200, 150).attr({fill: '#fff'});
var mskG = cv.group(mskHide, mskShow);

var bg = cv.circle(200, 200, 150).attr({fill: '#aaa'});
var customImg = cv.image('http://placehold.it/500/990000').attr({mask: mskG});

//when I drag the customImg, I want mskG fixed position
customImg.drag();

您可以在这里预览:http://codepen.io/rlog/pen/eKBlc

问题是:当我拖动customImg时,如何固定mskG的位置。

mskG 不用换costomImg

这个例子就是我想要的:http://codepen.io/rlog/pen/bAImu

谢谢!

【问题讨论】:

    标签: javascript html css svg snap.svg


    【解决方案1】:

    你基本上可以做你在第二个 codepen 中所做的事情。

    var cv = Snap('#cv').attr({height: '100%', width: '100%'});
    
    var mskHide = cv.rect().attr({height: '100%', width: '100%', left:0, top:0, fill: '#666'});
    var mskShow = cv.circle(200, 200, 150).attr({fill: '#fff'});
    var mskG = cv.group(mskHide, mskShow);
    
    
    var bg = cv.circle(200, 200, 150).attr({fill: '#aaa'});
    
    var customImg = cv.image('http://placehold.it/500/990000').attr({mask: mskG });
    
    
    customImg.drag( myDrag );
    function myDrag(dx,dy,x,y) {
      customImg.attr({ x: dx, y: dy })
    }
    

    codepen

    如果您想要与示例不同的拖动以包含存储的开始拖动位置,您可以将其修改如下...

    customImg.attr({ x: 0, y: 0})
    
    var move = function(dx,dy) {
    this.attr({
          x: +this.data('ox') + +dx,
          y: +this.data('oy') + +dy
        })
    } 
    
    var start = function(x,y) {
      this.data('ox', this.attr('x'));
      this.data('oy', this.attr('y'));
    }
    
    var end = function(x,y) {}  
    
    customImg.drag( move, start, end )
    

    codepen

    【讨论】:

    • 谢谢!但是 myDrag 在拖动时有一个小错误。 customImg.attr({ x: dx, y: dy })dxdy 可能不是 xy 的正确值。我该如何解决?
    • 太棒了!非常感谢^_^
    最近更新 更多