我在我的网页上使用了一个canvas元素,并且需要能够在每次单击时使用不同颜色的鼠标单击绘制圆圈。这是我的代码,它适用于某些网站,但不适用于其他网站。我的问题是我错过了什么工作?我知道代码中只有一种颜色,但就目前来说,我点击了整个画布并没有任何反应。
<head>
<title></title>
<meta charset="utf-8">
<script src="clickCircle.js"></script>
</head>
<body>
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw (event)">
</canvas>
</body>
class A(models.Model):
aname = models.CharField(max_length=64, verbose_name='name')
答案 0 :(得分:3)
以下是随机颜色生成器功能的示例 您还应该尝试以unobtrusive方式添加click事件侦听器。
var table = $('#mytable').DataTable({
//my settings here
}).on( 'search.dt', function () { updateGraph( GraphData ) ; } );
var canvas = document.getElementById("cirCanvas");
var context = canvas.getContext("2d");
canvas.addEventListener('click', draw, false);
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = randomColor();
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
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
};
}
#cirCanvas {
border: 1px solid black;
}
答案 1 :(得分:1)
以下是如何更改颜色 - 您可以随机化颜色:
Best way to generate a random color in javascript?
或使用固定颜色数组
colors = ["001100","AA0000","00BB00"];
使用
context.fillStyle = "#"+colors[Math.round(Math.random()*colors.length)];
随机版本:
var canvas = document.getElementById("cirCanvas"),
context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("circles").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
//window.draw = draw;
<div id="circles"></div>
<canvas id="cirCanvas" width="250" height="250" onclick="draw(event)">
</canvas>
答案 2 :(得分:0)
您必须实现一个能够生成随机颜色的函数。
只是使用......像这样:
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}