gpt4 book ai didi

javascript - 创建一个 angularjs 指令来包装 jquery tagcanvas 插件

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

我想实现一个动画词云。由于我没有找到任何 angular 或 Ionic 就绪插件来做我想做的事情,我决定(而且我发现学习它很有趣)为 jquery 代码创建一个 angular 包装器。插件是tagcanvas , 用法示例为 this

到目前为止我做了什么:

  • 我将 jquery js 文件添加到我的 index.html
  • 我创建了一个 js 文件,其中声明了我的指令,并将其添加到 index.html:

tagcanvas.js

angular.module('tagCanvas', [])

.directive('tagCanvas', function() {

return {

restrict: 'E',
link: function (scope, element, attrs) {


element.tagcanvas({


outlineColour: attrs.outlineColour,
reverse: attrs.reverse,
depth: attrs.depth,
maxSpeed: attrs.maxSpeed,
textFont: attrs.textFont,
textColour: attrs.textColour,
weightMode: attrs.weightMode,
weight: attrs.weight
}, attrs.canvas);



}
};

});

正如您在 codepen 示例中看到的,有一些我需要调用的属性,以及一个 html 元素 id canvas,我不知道如何在我的指令中调用它们。

我的第二个问题是我不知道如何创建和调用我想在我的标签云中显示的词。我看了很多教程,但我仍然不知道该怎么做。任何帮助将不胜感激。

最佳答案

首先,我不会将您的 Angular 应用程序和指令命名为相同的名称。它不仅令人困惑,而且可能无法正常工作。其次,虽然可能有很多方法可以解决这个问题,但我会这样做:

指令
(我已将指令更改为属性而不是元素,并为属性使用隔离范围。链接函数包装在 $timeout 中,以确保元素在尝试之前存在于 DOM 中调用 tagcanvas。)

.directive("tagCanvas", function($timeout) {
return {
restrict: "A",
scope: {
canvasId: "@",
outlineColour: "@",
reverse: "@",
depth: "@",
maxSpeed: "@",
textFont: "@",
textColour: "@",
weightMode: "@",
weight: "@"
},
link: function (scope, element) {
$timeout(function() {
element.tagcanvas({
outlineColour: scope.outlineColour,
reverse: scope.reverse,
depth: scope.depth,
maxSpeed: scope.maxSpeed,
textFont: scope.textFont,
weightMode: scope.weightMode,
weight: scope.weight
}, scope.canvasId);
});
}
};
})

控制者
(您可能希望从服务或其他存储中获取单词列表,但为了说明,我在 Controller 中硬编码了一个数组)

.controller("ctrl", function ($scope) {
$scope.wordList = [
{
href: "#",
fontSize: "2.83ex",
text: "1000"
}, {
href: "#",
fontSize: "4.8ex",
text: "example"
}, {
href: "#",
fontSize: "8.77ex",
text: "gif"
}, {
href: "#",
fontSize: "2.83ex",
text: "svg"
}, {
href: "#",
fontSize: "8.77ex",
text: "jpg"
}, {
href: "#",
fontSize: "10.68ex",
text: "png"
}, {
href: "#",
fontSize: "2.83ex",
text: "bmp"
}, {
href: "#",
fontSize: "4.8ex",
text: "img"
}
];
})

html

<div>
<canvas width="300"
height="300"
id="myCanvas"
tag-canvas
canvas-id="tags"
outline-colour="#ff00ff"
text-font="Arial"
text-colour="#ff00ff"
reverse="true"
depth="0.8"
max-speed="0.05"
weight-mode="both"
weight="true"></canvas>
</div>
<div id="tags" style="font-size: 50%;">
<a ng-repeat="word in wordList" href="{{word.href}}" style="font-size: {{word.fontSize}}">{{word.text}}</a>
</div>

关于javascript - 创建一个 angularjs 指令来包装 jquery tagcanvas 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772936/

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