我已经在类似于“ MS Paint”的在线绘图平台的背景下为画布制作了网格。对于网格,用户必须能够输入构成网格的正方形的大小以及网格的不透明度的值。我正在使用ngModel
(用于用户输入)和ngStyle
。
以下是与网格有关的html代码的一部分:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="smallGrid" patternUnits="userSpaceOnUse" [ngStyle]="setSizePattern()">
<path id="myPath" fill="none" stroke="black" stroke-width="0.7" [ngStyle]="setSizePath()" />
</pattern>
</defs>
<rect id="myGrid" width="100%" height="100%" fill="url(#smallGrid)" [ngStyle]="setStyle()"/>
</svg>
<pattern>
具有属性'width'和'height',而<path>
具有属性'd';这些是我要修改的属性。
以下是相关方法:
setSizePath(): object {
const pathString = '"M' + this.userInputGridSize + ',0 L0,0 0,' + this.userInputGridSize + '"';
const cssPath = 'path(' + pathString + ')';
return {d: cssPath};
}
setSizePattern(): object {
return {width: this.userInputGridSize,
height: this.userInputGridSize};
}
模板<path>
属性d
是d="MX,0 L0,0 0,X"
,其中X
是组成网格的正方形的大小。 width
中的height
和<pattern>
也必须是X
。
当它在html文件中手动设置时,它有效:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern width="10" height="10" id="smallGrid" patternUnits="userSpaceOnUse" [ngStyle]="setSizePattern()">
<path id="myPath" d="M10,0 L0,0 0,10" fill="none" stroke="black" stroke-width="0.7" [ngStyle]="setSizePath()" />
</pattern>
</defs>
<rect id="myGrid" width="100%" height="100%" fill="url(#smallGrid)" [ngStyle]="setStyle()"/>
</svg>
这将显示一个大小为10(我认为是px)正方形的网格。
我似乎无法对其进行修改。
相反,在setStyle()
中找到的<rect>
函数可以正常工作:
setStyle(): object {
return {opacity: this.userInputOpacity};
}
哦,这是一个不可接受的版本(由于getElementBy ...的原因),它也可以工作:
// Functional but code smell size setter
setSizeSmell(): void {
const gridElement = document.getElementById('smallGrid');
const pathElement = document.getElementById('myPath');
const value = (document.getElementById('sizeInput') as HTMLInputElement).value;
const pathValue = "M"+ value + ",0 L0,0 0," + value;
if (gridElement && pathElement) {
pathElement.setAttribute("d", pathValue);
gridElement.setAttribute("width", value);
gridElement.setAttribute("height", value);
}
}
sizeInput
是用户在其中输入网格平方大小的所需值的字段。但是我们不允许使用这些方法,因为它们是反模式的。