我正在使用 canvas fillrect 函数绘制多个矩形。我现在正在对坐标进行硬编码,但是是否可以像对函数的函数调用一样将它们传递给填充矩形?例如,如果我有 10 组坐标,我可以使用 for 循环或其他方式将其传递给 fillRect 吗?
<body>
<canvas id="canvas1" width="1224" height="770" position="absolute" style="border:1px solid #d3d3d3;">
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(330,0,150,75);
ctx.fillStyle = "#FF4500";
ctx.fillRect(30,80,150,75);
</script>
最佳答案
是的,像这样很容易:
<body>
<canvas id="canvas1" width="1224" height="770" position="absolute" style="border:1px solid #d3d3d3;">
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
function Generate(color,x,y,w,h)
{
ctx.fillStyle = color;
ctx.fillRect(x,y,w,h)
};
for(i=0;i<10;i++){
var height=100*i;
var width=50*i;
var x=i+(i*100);
var y=i+(i*120);
Generate("red",x,y,width,height);
}
</script>
</canvas>
</body>
关于javascript - 将值传递给 FillRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52894346/