Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用HTML5画布获得多色矩形?_Javascript_Css_Html_Canvas - Fatal编程技术网

Javascript 如何使用HTML5画布获得多色矩形?

Javascript 如何使用HTML5画布获得多色矩形?,javascript,css,html,canvas,Javascript,Css,Html,Canvas,我正在尝试用不同的颜色绘制6X6的正方形。但是新的颜色覆盖了旧的颜色。我想为每个方块添加eventhandler <canvas id="myCanvas" width="3000" height="1500" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> 您的浏览器不支持HTML5画布标记。 JavaScript: va

我正在尝试用不同的颜色绘制6X6的正方形。但是新的颜色覆盖了旧的颜色。我想为每个方块添加eventhandler

<canvas id="myCanvas" width="3000" height="1500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

您的浏览器不支持HTML5画布标记。
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;

}
var-xPoint=30;
var-yPoint=30;
var c=document.getElementsByTagName('canvas')[0];
var ctx=c.getContext(“2d”);

对于(var i=1;i您混淆了方法中参数的顺序。它应该是:

ctx.rect(txPoint, tyPoint, 20, 20);
前两个参数是矩形左上角的x和y坐标,其余参数是矩形的宽度和高度


演示:

删除JS中的以下行:

   ctx.beginPath();
现在它显示了正确的网格,因为您已停止覆盖

检查这里: