gpt4 book ai didi

javascript - 如何使用 HTML5 Canvas 获取多个颜色矩形?

转载 作者:搜寻专家 更新时间:2023-10-31 08:44:16 25 4
gpt4 key购买 nike

我正在尝试用不同的颜色绘制 6X6 的正方形。但是新颜色压倒旧颜色。我想为每个方 block 添加事件处理程序。

<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;

}

这是 fiddle .

最佳答案

您混淆了 rect 中的参数顺序方法。应该是:

ctx.rect(txPoint, tyPoint, 20, 20);

前两个参数为矩形左上角的x和y坐标,其余为矩形的宽和高。

演示: http://jsfiddle.net/j9c5P/413/

关于javascript - 如何使用 HTML5 Canvas 获取多个颜色矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28607434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com