Reputation: 65
I'm trying to draw 6X6 squares with different colors. But the new color overriding the old one. And i want to add eventhandler for every square.
<canvas id="myCanvas" width="3000" height="1500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
JavaScript:
var xPoint = 30;
var yPoint = 30;
var c = document.getElementsByTagName('canvas')[0];
var ctx = c.getContext("2d");
for(var i =1; i<=6;i++)
{
var tyPoint = yPoint * i;
for(var j=1;j<=6;j++)
{
var txPoint = xPoint * j;
var colorcode = CalculateHEX();
ctx.beginPath();
ctx.fillStyle = colorcode ;
ctx.rect(20, 20, txPoint , tyPoint );
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
function CalculateHEX()
{
alert('HEX');
var rgbCode ="#";
for(var c = 0;c< 3;c++)
{
var y = Math.floor((Math.random() * 255) + 1);
rgbCode = rgbCode + Number(y).toString(16);
}
return rgbCode;
}
Here is the fiddle.
Upvotes: 4
Views: 3089
Reputation: 86
Delete following line in your JS:
ctx.beginPath();
Now it shows the correct grid because you stopped overwriting.
https://jsfiddle.net/j9c5P/414/
Upvotes: 0
Reputation: 193261
You confused the order of parameters in the rect
method. It should be:
ctx.rect(txPoint, tyPoint, 20, 20);
The first two arguments are x and y coordinates of the upper-left corner of the rectangle, and the rest are rectangle width and height.
Demo: http://jsfiddle.net/j9c5P/413/
Upvotes: 2