gpt4 book ai didi

Javascript - Canvas - 单击按钮时创建圆圈

转载 作者:行者123 更新时间:2023-12-01 02:41:58 25 4
gpt4 key购买 nike

我试图强制我的 html 按钮在 Canvas 区域上画一个圆圈,但我不知道我做错了什么。有人可以指点一下吗?

JavaScript

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Funkcja
function drawCircle(size,xPos,Ypos,colour){ //draw circle
var xPos = Math.floor(Math.random() * 501);
var yPos = Math.floor(Math.random() * 501);
var size = Math.floor(Math.random() * 100);
var colour = '#' + Math.random().toString(16).substring(4); // random colour;
ctx.beginPath();
ctx.arc(xPos,yPos,size,0,2*Math.PI);
ctx.fillStyle = colour;
ctx.fill();
}

HTML

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="site.css">
<script type="text/javascript" src="site.js"></script>
</head>

<body>
<button style="margin:0;padding:0;position:relative;left:50px;top:50px;" onclick="drawCircle()">Draw Random Circle</button><br>
<div style = "width:500px; height:150px; margin:0 auto; padding:5px;">
<canvas id = "canvasArea" width = "500" height = "550" style = "border:2px solid black"></canvas>
</div>
</body> </html>

最佳答案

正如迭戈所说:错误的 ID。

此外,您最好在仅在页面加载后触发的函数中使用 HTML 元素。

编辑:Math.random 生成 0 到 1 之间的数字。所以让我们跳过“0”。所以是来自字符 2 的子字符串,长度为 6 个字符。

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="site.css">
<script type="text/javascript">
// global variables
var canvas;
var ctx;
// You do not have permission to read from ( nor write to ) HTML elements before the DOM is loaded.
window.onload = function() {
canvas = document.getElementById("canvasArea");
ctx = canvas.getContext("2d");
}
// Funkcja
function drawCircle(size, xPos, Ypos, colour) { //draw circle
var xPos = Math.floor(Math.random() * 501);
var yPos = Math.floor(Math.random() * 501);
var size = Math.floor(Math.random() * 100);
var colour = '#' + Math.random().toString(16).substr(2,6); // random colour;
// var colour = '#' + Math.random().toString(16).substring(4); // random colour;
ctx.beginPath();
ctx.arc(xPos, yPos, size, 0, 2 * Math.PI);
ctx.fillStyle = colour;
ctx.fill();
}
</script>
</head>
<body>
<button style="margin:0;padding:0;position:relative;left:50px;top:50px;" onclick="drawCircle()">Draw Random Circle</button><br>
<div style="width:500px; height:150px; margin:0 auto; padding:5px;">
<canvas id="canvasArea" width="500" height="550" style="border:2px solid black"></canvas>
</div>
</body>
</html>

关于Javascript - Canvas - 单击按钮时创建圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513336/

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