【发布时间】:2017-09-30 00:17:41
【问题描述】:
我正在尝试使用 html5 和 javascript 开发一个简单的画布应用程序。我想根据鼠标在画布中单击的位置制作一个圆圈。每次用户在画布中单击时,都应绘制一个圆圈。此外,圆圈的颜色需要随机选择。我已经编写了随机颜色和位置函数来获取鼠标在画布中的 x 和 y 位置。但是当我运行时什么都没有发生。
这是我的html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="circle.js"></script>
<style type="text/css">
#testCanvas {
border: 2px solid;
}
</style>
</head>
<body>
<canvas id="testCanvas" width="400" height="400"> </canvas>
</body>
这是我的 javascript 代码:
window.onload = init;
function init() {
// access the canvas element and its context
var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
// fill a circle
context.beginPath();
context.arc(posx,posy, 30, 0, 2 * Math.PI, true);
context.fill();
context.closePath();
}
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
【问题讨论】:
标签: javascript html canvas