开发者

HTML 5 canvas random opacity issue

Could someone explain to me why this is fail.

Trying to get the opacity to load as a random value.

I cannot get this to render in anything but black even though the alert is clearly showing that I'm getting values between 0.00 and 1.00

Important Code:

alert(Math.round(Math.random() * 100) / 100); <-- Tests to see if output is what it's supposed to be

ctx.fillStyle = "rgba(0, 0, 0, Math.round(Math.random() * 100) / 100)"; <-- generates as black, always

Tested: 1. Set opacity to random variables between 0-1 worked fine 2. Added the above alert box just to see if ranges were acceptable

    <!DOCTYPE html>
<html>
 <head>
  <script type="application/javascript">

//Names must match each element in your html file
var shapeName = new Object();

shapeName = {sWidth: 50, sHeight: 50, nShapes: 3, bSpacing: 10};

function getHeight(){
    return  document.getElementById("canvas1").offsetHeight;
}

function getWidth(){
    return document.getElementById("canvas1").offsetWidth;
}

function draw() {
 //grabbing the height and width of canvas, note that border is effected by this(ex. width of 400 with border 1 will result 402)
 var cWidth = document.getElementById("canvas1").offsetHeight;
 var cHeight = document.getElementById("canvas1").offsetHe开发者_JAVA百科ight;

 var canvas = document.getElementById("canvas1");
 var ctx = canvas.getContext("2d");
 alert(Math.round(Math.random() * 100) / 100);
 ctx.fillStyle = "rgba(0, 0, 0, Math.round(Math.random() * 100) / 100)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgba(0, 0, 300, 1.0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 60, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgb(0,200,0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 120, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);

 ctx.fillStyle = "rgb(222,25,0)";
 ctx.fillRect (((cWidth / 2) + (shapeName.sWidth / 2)) - (shapeName.sWidth * shapeName.nShapes + shapeName.bSpacing * shapeName.nShapes) / 2 + 180, (cHeight / 2) - (shapeName.sHeight / 2), shapeName.sWidth, shapeName.sHeight);
}
  </script>
 </head>
 <body onload="draw()">
   <canvas id="canvas1" width="400" height="300" style="border: 1px solid;"></canvas>
</body>
</html>


You can't put the javascript for Math.random() inside the CSS style string. That needs to be concatenated to the string.

Try:

ctx.fillStyle = "rgba(0, 0, 0, " + Math.random() + ")";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜