gpt4 book ai didi

javascript - 在 Canvas 上的形状中制作随机颜色

转载 作者:行者123 更新时间:2023-11-27 23:33:53 25 4
gpt4 key购买 nike

我有一个在 Canvas 上制作随机形状的代码。我想用随机颜色填充形状,为此我做了这个:

var R=(Math.floor(Math.random() * 255);
var G=(Math.floor(Math.random() * 255);
var B=(Math.floor(Math.random() * 255);
var randColor='rgb(' + R +', ' + G + ',' + B +')';

context.fillStyle=randColor;

我把它放在生成形状的函数中,但没有运气。例如,我只将其放在 makeRect 函数中,但它也应该放在 makeCircle 函数中。谁能告诉我我在这里做错了什么?

这是我的 HTML:

<head>
<link href="design.css" rel="stylesheet" />
</head>

<body>
<h4> Enter below, and then press the canvas to save your work</h4>
<canvas id="canvas" width="1000" height="750"></canvas>
<br/>
<br/>
<span>
How many Circles do you want?
<input id="inCircle" />
</span>
<br/>How many Squers do you want?
<input id="inSquer" />
<br/>
<button id="creat">Creat My Work</button>

<script src="js.js"></script>
</body>

</html>

这是我的 JavaScript:

var drawing = document.getElementById("canvas");
var context = drawing.getContext("2d");
var inSquer = document.getElementById("inSquer");
var inCircle = document.getElementById("inCircle");
var button = document.getElementById("creat");


button.addEventListener("click", function() {


paint(parseInt(inSquer.value), parseInt(inCircle.value));
});

drawing.addEventListener("click", function() {
saveImage();
});


function saveImage() {
window.location = drawing.toDataURL("image/jpeg");
}

function paint(numOfRect, numOfCirc) {

for (var makeIt = 0; makeIt < numOfRect; makeIt++) {
makeRect(drawing, context);
makeCircle(drawing, context);
}
}

function makeCircle(drawing, context) {

var radius = Math.floor(Math.random() * 100);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);

context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fillStyle = "blue";
context.fill();
}

function makeRect(drawing, context) {

var w = Math.floor(Math.random() * 100);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);

var R=(Math.floor(Math.random() * 255);
var G=(Math.floor(Math.random() * 255);
var B=(Math.floor(Math.random() * 255);
var randColor='rgb(' + R +', ' + G + ',' + B +')';

context.fillStyle=randColor;

/*context.fillStyle="green";*/
context.fillRect(x, y, w, w);
}

这是我的 CSS:

h4{
text-align: center;
}
#canvas{
margin-left: 250px;
border: 1px solid black;

}

最佳答案

你的 JS 的第一部分缺少一些括号。

var R = (Math.floor(Math.random() * 255)),
G = (Math.floor(Math.random() * 255)),
B = (Math.floor(Math.random() * 255)),
randColor = 'rgb(' + R + ', ' + G + ',' + B + ')';

关于javascript - 在 Canvas 上的形状中制作随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293292/

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