问题
I am trying to build simon game using html5 canvas and pure javascript. I have managed to get the simon game UI using html5 canvas. My next step is to make the four components light up randomly. I am not sure if this is even possible with html5 canvas or probably my approach is wrong. Any hints in the right direction will be of great help. My code is as follows codepen link: http://codepen.io/anon/pen/QEdPRN?editors=1010
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
//bigger circle
ctx.beginPath();
ctx.arc(235,230,140,0,2*Math.PI);
ctx.fillStyle = '#000';
ctx.fill();
ctx.stroke();
//smaller circle
ctx.beginPath();
ctx.arc(235,230,60,0,2*Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.stroke();
//draw the four arcs
var x = [240,240,230,230];
var y = [240,225,225,240];
var start = [0,1.5*Math.PI,1*Math.PI,0.5*Math.PI];
var end = [0.5*Math.PI,0,1.5*Math.PI,1*Math.PI];
var color = ["blue","red","green","yellow"];
var draw = function (a,b,c,d,e) {
ctx.beginPath();
ctx.arc(a,b,90,c,d);
ctx.lineWidth = 50;
ctx.strokeStyle = e;
ctx.stroke();
}
function drawSimon() {
for(var i=0;i<4;i++){
draw(x[i],y[i],start[i],end[i],color[i]);
}
}
drawSimon();
回答1:
Your first problem: This is just a static image.
You only call drawSimon() once, thus it only gets drawn once. To fix this, you need to use requestAnimationFrame or setInterval (preferably the first).
requestAnimationFrame is like a simple method call, but delays the method, so it lines up with the screen's framerate. You need to call drawSimon from inside drawSimon with this.
function drawSimon() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); //Clear the screen
//Draw the simon here
requestAnimationFrame(drawSimon);
}
drawSimon();
Next you want to choose a random color and make it lighter. There's a problem with this. Your colors are all already pure colors, you can't make them brighter. You need to use darker colors (example: rgb(150, 0, 0) instead of red). Then you need to choose a random index between 0 and 3 (inclusively), and make the color in that place brighter.
var index = Math.floor(Math.random() * 4);
switch (index) {
case 0:
color[0] = "blue";
break;
case 1:
color[0] = "red";
break;
case 2:
color[0] = "green";
break;
case 3:
color[0] = "yellow";
break;
}
Third step: make the colors change back.
You could achieve this with a time counter. Each time you set a color to brighter save the time this was done. Each frame, check the time between the current time and the last time you changed to colors, and if it's over a specific limit, set them back the same way you did with the brighter colors.
//global scope:
var lastChange = 0;
//Change a color to lighter here
lastChange = Date.now();
//Later in the code
if (Date.now() - lastChange > maxTime) {
//Change colors back here
}
来源:https://stackoverflow.com/questions/38061330/how-to-change-color-of-circle-temporarily-in-html5-canvas