如何更改画布中特定形状的属性?

时间:2014-01-11 06:05:03

标签: javascript css html5 css3 canvas

我试图改变画布中特定对象的阴影(不是全部)。问题是,当我试图将阴影赋予特定对象时,自动所有其他对象也会获得阴影。这是我的代码

 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条件中的命令会更改画布中所有形状的属性。那么是否有任何其他语法可以通过它来改变画布中特定形状的阴影

2 个答案:

答案 0 :(得分:0)

您始终可以在画布上下文中使用本机js函数setShadow或任何其他函数。您可以看到here正在运行。

答案 1 :(得分:0)

在想要用阴影绘制对象之前,需要设置阴影。之后,您需要在绘制其余对象之前删除阴影。

最简单的方法是将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...