【发布时间】:2015-12-13 18:20:19
【问题描述】:
我想做的是一个“addEventListener”函数。单击画布并出现雨滴时,会发出晃动的声音。所以无论你点击多少次,声音都会一直播放。
我不知道它叫什么,是我的教授建议的。然而,当我梳理谷歌时,我发现的只是按钮点击或 Jquery 的东西。我不想要按钮,也不允许使用 Jquery。
一如既往,我只寻求正确的方向。
感谢你们迄今为止给我的所有帮助。
var canvas;
var context;
var drops = [];
var squares = [];
function Drop(x,y,color){
this.x = x;
this.y = y;
this.color = color;
this.dy = Math.random();
}
function Square(x,y,w,color){
this.sx = x;
this.sy = y;
this.sw = w;
this.color = color;
this.qy = Math.random();
}
function init(){
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
alert("Hello!\nClick on the screen for rain drops!");
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
resizeCanvas();
canvas.onclick = function(event){
handleClick(event.clientX, event.clientY);
};
setInterval(handleClick,5);
}
function handleClick(x,y,w){
var found = false;
for(var i = 0; i<drops.length; i++){
d = Math.sqrt((drops[i].x-x)*(drops[i].x-x) + (drops[i].y-y)*(drops[i].y-y));
if(d<=5){
drops.splice(i,1);
found = true;
}
}
fillBackgroundColor();
if(!found){
var colors = ["#000080", "#add8e6", "blue"];
var color = colors[Math.floor(Math.random()*colors.length)];
drops.push(new Drop(x,y,color));
squares.push(new Square(x,y,w,color));
}
for(var i = 0; i<drops.length; i++){
drawDrop(drops[i]);
}
for(var i = 0; i<squares.length; i++){
drawSquare(squares[i]);
}
}
function drawDrop(drop){
context.beginPath();
context.arc(drop.x, drop.y, 5, 0, Math.PI);
context.fillStyle = drop.color;
context.moveTo(drop.x - 5, drop.y);
context.lineTo(drop.x, drop.y - 7);
context.lineTo(drop.x + 5, drop.y);
context.closePath();
context.fill();
if (drop.y + drop.dy > canvas.height || drop.y + drop.dy < 0)
drop.dy != -drop.dy;
drop.y += drop.dy;
};
function drawSquare(square){
var sw = Math.floor(4);
var sx = Math.floor(Math.random() * canvas.width);
var sy = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.rect(sx, sy, sw, sw);
context.fillStyle = '#add8e6';
context.fill();
};
function fillBackgroundColor(){
context.fillStyle = 'gray';
context.fillRect(0,0,canvas.width,canvas.height);
}
function resizeCanvas(){
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
fillBackgroundColor();
for(var i = 0; i<drops.length; i++){
drawDrop(drops[i]);
}
for(var i = 0; i<squares.length; i++){
drawSquare(squares[i]);
}
}
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
window.onload = init;
</script>
</head>
<body>
<canvas id='canvas' width=500 height=500></canvas>
</body>
【问题讨论】:
标签: html audio canvas html5-audio