简体   繁体   English

在Angular.js中将SVG拟合到背景图像div

[英]Fitting an svg to background-image div in angular.js

How do I fit an SVG as background-image to a DIV container that could be of variable size? 如何将SVG作为背景图像安装到大小可变的DIV容器中? The SVG is generated dynamically, so I actually need to pass the width and height of the DIV container to my SVG-generating Javascript function. SVG是动态生成的,因此我实际上需要将DIV容器的宽度和高度传递给我的SVG生成Javascript函数。

I'm using angular.js, so I would also like to do it in the right way. 我正在使用angular.js,所以我也想以正确的方式来做。 :) :)

There's not much to add re: code, but in the spirit of SO questions needing code examples, here is where I assign the SVG: re:代码添加的内容不多,但是出于需要代码示例的SO问题的精神,这是我分配SVG的地方:

var str = 'url("data:image/svg+xml;utf8,'+s+'")';    
$("#token-creator").css({'background-image': str, 'background-repeat':'no-repeat', 'background-opacity': .04});

If you want to do this the "Angular way", you should consider creating a directive . 如果要以“角度方式”执行此操作,则应考虑创建directive

JS - (Directive) JS-(指令)

app.directive('backImg', function(){

    return function(scope, element, attrs){

        attrs.$observe('backImg', function(value) {

            var url = attrs.backImg;
            var size = attrs.backImgSize || 'cover';
            var width = attrs.backImgWidth;
            var height = attrs.backImgHeight;

            element.css({

                'background-repeat' : 'no-repeat',
                'background-image': 'url(' + value +')',
                'background-size' : size,
                '-webkit-background-size': size,
                '-moz-background-size': size,
                '-ms-background-size': size,
                'width': width,
                'height': height

            });

        });

    };

});

Markup (View) 标记(查看)

where {{svg}} is a $scope variable in your controller: 其中{{svg}}是控制器中的$scope变量:

<div back-img="{{svg}}" back-img-size="contain" back-img-width="500px" back-img-height="500px"></div>

Plunk : http://plnkr.co/edit/jw48qHwk7A2ctHBQT1TW?p=preview Plunk: http ://plnkr.co/edit/jw48qHwk7A2ctHBQT1TW?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM