我正在基于 Canvas 构建自定义 AngularJS 1 指令。但我看不到我在 Canvas 上绘制的矩形:
angular.module('loloof64.chess_diagram', [])
.directive('chessDiagram', function() {
return {
restrict: "E",
template: '<canvas width="{{size}}" height="{{size}}"></canvas>',
scope: {
size: '@'
},
compile: function(element, attrs) {
drawBackground = function(scope, canvasCtx) {
canvasCtx.fillStyle = "#DD55CC";
canvasCtx.fillRect(0, 0, scope.size, scope.size);
};
return function(scope, element, attrs) {
scope.size = scope.size - scope.size % 9;
scope.cellSize = Math.floor(scope.size / 9);
canvas = element[0].children[0];
ctx = canvas.getContext("2d");
drawBackground(scope, ctx);
};
}
};
});
最佳答案
这里的问题是您在 dom 完成渲染之前调用 fillRect
。 StackOverFlow 上已经有一个线程为此。
在 $timeout
内以零延迟对 drawBackground
进行调用。
$timeout(function() {
drawBackground(scope, ctx);
});
并且不要忘记在指令中注入(inject) $timeout:
.directive('chessDiagram', function($timeout) {
另外scope.size
是NaN
。给它一个值可能在html中像这样
<chess-diagram size="100"></chess-diagram>
关于javascript - 在 angularJS 中使用自定义 Canvas 指令不会显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246187/