2014-01-11 35 views
-1

我想改變畫布中特定對象的陰影(不是全部)。問題是,當我試圖給特定對象的陰影,然後自動所有其他對象也獲得陰影。這是我的代碼如何更改畫布中特定形狀的屬性?

CanvasState.prototype.draw = function() { 
    // if our state is invalid, redraw and validate! 
    if (!this.valid) { 
    var ctx = this.ctx; 
    var shapes = this.shapes; 
    this.clear(); 

    // ** Add stuff you want drawn in the background all the time here ** 

    // draw all shapes 
    var l = shapes.length; 
    for (var i = 0; i < l; i++) { 
     var shape = shapes[i]; 
     // We can skip the drawing of elements that have moved off the screen: 
     if (shape.x > this.width || shape.y > this.height || 
      shape.x + shape.w < 0 || shape.y + shape.h < 0) continue; 
     shapes[i].draw(ctx); 
    } 

    // draw selection 
    // right now this is just a stroke along the edge of the selected Shape 
    if (this.selection != null) { 
     var ctx = this.ctx; 
     ctx.strokeStyle = this.selectionColor; 
     ctx.lineWidth = this.selectionWidth; 
     var mySel = this.selection; 
     temp = mySel; 

     if (this.light) { 
      ctx.shadowBlur=20; 
      ctx.shadowColor="yellow"; 
     }; 

     ctx.strokeRect(mySel.x -15,mySel.y -15 ,mySel.w,mySel.h); 

     if (del==1) { 
     del=0; 
     mySel.x=0; 
     mySel.y=0; 
     mySel.w=0; 
     mySel.h=0; 
     mySel.r=0; 
     mySel.shapes.draw(ctx); 

     }; 

     if (chcolor == 1) { 
     chcolor=0; 
     mySel.fill = pixelColor; 
     mySel.shapes.draw(ctx); 
     }; 

    } 

    // ** Add stuff you want drawn on top all the time here ** 

    this.valid = true; 
    } 
} 

有,如果條件爲this.light決定有陰影或沒有。

if (this.light) { 
      ctx.shadowBlur=20; 
      ctx.shadowColor="yellow"; 
     }; 

if條件中的命令更改畫布中所有形狀的屬性。那麼是否還有其他語法可以通過它來更改畫布中特定形狀的陰影

回答

1

您需要在您想要用陰影繪製對象之前設置陰影。之後,您需要在繪製剩餘的對象之前移除陰影。

最簡單的方法是使用save()/restore()結合陰影。例如要集成,你可以嘗試這樣的事情(根據需要進行調整):

/// enable shadow for next drawn object 
if (this.light) { 
    ctx.save(); 
    ctx.shadowBlur=20; 
    ctx.shadowColor="yellow"; 
}; 

/// draw object/shape 
ctx.strokeRect(mySel.x -15,mySel.y -15 ,mySel.w,mySel.h); 

/// remove shadow 
if (this.light) { 
    ctx.restore(); 
}; 

... other code... 
+0

這些改變已經正常運行。但只適用於單一形狀。當想要在其他形狀上操作時,先前的形狀再次被禁用。有沒有像ctx.mySel.shadowBlur的東西?我們能做到嗎? –

0

您可以隨時在畫布上下文中使用原生js函數setShadow或其他語言。您可以在行動中看到它here

+0

你可以做同樣的形狀? –

+0

@ketankhandagale呀...你可以做同樣的 –