簡體   English   中英

angular中的圖像更改灰度(滑塊)

[英]Image change greyscale (Slider) in angular

我正在嘗試使用 slider 控件將圖像更改為灰度和棕褐色

這是我的 html 代碼

       <div class="card-body">
        <input id="sepia" type="range" oninput="set(this, 'sepia');" value="0" step="0.1" min="0" max="1"> Sepia <span id="Amount_sepia">(0)</span><br/>
        <input id="grayscale" type="range" oninput="set(this, 'grayscale');" value="0" step="0.1" min="0" max="1"> Grayscale <span id="Amount_grayscale">(0)</span><br/>
      </div>

              <img class="img-fluid" id="img_prev" src="{{actualImage}}" *ngIf="!this.showCropper" />
                <image-cropper id="img_prev"  class="imageclass" *ngIf="this.showCropper" 
                        [autoCrop]="false"
                          [imageChangedEvent]="imageChangedEvent"
                           [maintainAspectRatio]="true"
                           [aspectRatio]="4 / 3"
                           [resizeToWidth]="256"
                           [cropperMinWidth]="128"
                            [onlyScaleDown]="true"
                           format="png"
                           (imageCropped)="imageCropped($event)"
                           (imageLoaded)="imageLoaded()"
                           (cropperReady)="cropperReady()"
                           (loadImageFailed)="loadImageFailed()" style="max-height:500px"> 
                </image-cropper>

這是我的 ts

public set(e,f){
    document.getElementById('img_prev').style["filter"] = f+"("+e.value+")";
    document.getElementById('Amount_'+f).innerHTML="("+e.value+")";
 }

我收到錯誤

(index):13 Uncaught ReferenceError: set is not defined
at HTMLInputElement.oninput ((index):13)

為什么不使用“角度方式”?

你聲明了兩個變量

  sepia=0;
  grayScale=0;

並且只需使用[(ngModel)][style.filter]

<input id="sepia" type="range" [(ngModel)]="sepia" 
    step="0.1" min="0" max="1"> Sepia
    <span id="Amount_sepia">({{sepia}})</span>
<br/>
<input id="grayscale" type="range" [(ngModel)]="grayScale" 
    step="0.1" min="0" max="1"> Grayscale
<span id="Amount_grayscale">({{grayScale}})</span>
<br/>
<img [style.filter]="'grayscale('+grayScale+') sepia('+sepia+')'" 
    src="https://picsum.photos/300/300?random=1">

查看簡單的堆棧閃電戰

在上面的示例中,使用了oninput屬性,它是一個全局事件屬性 這通常與 vanilla js 一起使用,但在 Angular 中有另一種方法可以在 TypeScript 代碼中調用 function:事件綁定。

在 Angular 中,沒有使用全局事件屬性,而是使用 Angular 的事件綁定特性綁定到DOM 事件

它遵循oninput="set(this, 'sepia');" 應更改為(input)="set(..params..)"的格式。

然而,一些調整似乎是必要的。 例如,輸入綁定中的this作為參數不起作用,很可能$event將包含必要的信息。 另一方面,不建議使用document.getElementById訪問本機 DOM 元素,我建議使用ViewChild代替它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM