clearRect() and shadowColor() (CANVAS)

clearRect()

The clearRect() method is used to clear a portion of  the rectangle. It clears the specified pixels within the given rectangle. The following syntax can be used to clear a rectangle on a canvas:
clearRect(x, y, width, height);

Consider a following code to clear a part of a rectangle created on the canvas having ID, myCanvas:

<!DOCTYPE HTML>
<HTML>
<HEAD>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-9961622779713084",
    enable_page_level_ads: true
  });
</script>
<TITLE> clearRect/TITLE>
</HEAD>
<BODY>
<canvas id="gameCanvas" width="500" height="300" Style="border:1px solid black">
</canvas>
<SCRIPT>
var c=document.getElementById("gameCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(30, 40, 120, 120);
ctx.clearRect(50, 60, 40, 40);
</SCRIPT>
</BODY>
</HTML>

Result:


shadowColor

Once you have drawn a shape on the canvas, you may want to make it more stylish by casting  a shadow on it. To cast a shadow of a graphic object  on the canvas,  you need to specify the color of the shadow.  You need to specify how blurred you want your shadow to be. The shadowColor property is used to set the color for the shadows appearing on the graphic objects and the shadowBlur property  is used to set the blur level for the shadows.

You can use the following syntax to use the shadowColor property:

shadowColor="color";

In the preceding syntax, color specifies the color that will be applied on the  shadows. The default value of the shadowColor property is solid black.

You need to use the following syntax to define the shadowBlur property:
shadowBlur="number";

In the preceding syntax number specifies the blur level of the shadow. It can accept the integer values
such as 1, 2 and 20. The default value is 0.

Consider the following code for applying the shadows on the rectangle:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE> shadowBlur</TITLE>
</HEAD>
<BODY>
<canvas id="gameCanvas" width="500" height="300" Style="border:1px solid black">
</canvas>
<SCRIPT>
var c=document.getElementById("gameCanvas");
var ctx=c.getContext("2d");
ctx.shadowBlur=40;
ctx.fillStyle="red";
ctx.shadowColor="black";
ctx.fillRect(20,20,100,80);
ctx.shadowColor="blue";
ctx.fillRect(140,20,100,80);
</SCRIPT>
</BODY>
</HTML>


Result:



About Codingwelove

Codingwelove
Recommended Posts × +

0 comments:

Post a Comment