So I want a rectangle of my canvas to change the color from black to yellow, to show that this same part have received an information. There is two rectangles from 2 diferent paths, and I want them to change the color in a random way.
If one rectangle is "0" and the other is "1", for example, when I press the button "Begin", math.random() will choose it to be 1 and rectangle "1" will change it's color from black to yellow. The loop will happen again and if math.random() choose it to be 0, now it's the rectangle 0 that will change it's color. And so on, until I press the "End" button.
This is what I tried to write on javascript:
iniciarButton.onclick = function (e) {
iniciarButton.disabled = true;
pararButton.disabled = false;
for (;;) {
var numAleat = Math.floor(Math.random() * 2);
if (numAleat === 1) {
context.fillStyle = "yellow";
context.fillRect(715,140,10,15);
context.fillStyle = "black";
context.fillRect(642,80,15,10);
} else {
context.fillStyle = "yellow";
context.fillRect(642,80,15,10);
context.fillStyle = "black";
context.fillRect(715,140,10,15);
}
if (iniciarButton.disabled === false) break;
}
};
pararButton.onclick = function (e) {
pararButton.disabled = true;
iniciarButton.disabled = false;
};
The problem is that it isn't working the way I expected it. When I press the "begin" button it enters on a loop that ends on one rectangle yellow and the other black and not like blinking in a random way.
Related
I have an HTML canvas element that a user can draw on, and I want to change the fill color of the canvas when the refresh icon is clicked, and it set it to a different color depending on the body ID.
Currently the onClick function is changing the body ID and body color as a result but it is not updating the canvas fill color. Does anyone have any ideas.
I'm fairly new to HTML canvas and not really used it much before so any help is appreciated.
I think it is this bit of code that is wrong.
function refresh() {
const colors = ["blue", "red", "green", "pink"];
const random = Math.floor(Math.random() * colors.length);
document.body.id = colors[random];
var bodyid = document.body.id;
console.log(bodyid);
var bridge = document.getElementById("canvas"),
bridgeCanvas = bridge.getContext('2d');
if(bodyid == 'red'){
bridgeCanvas.fillStyle = "#6ecbff";
} else if(bodyid == 'blue') {
bridgeCanvas.fillStyle = "#fedcdb";
} else if(bodyid == 'green') {
bridgeCanvas.fillStyle = "#fefd55";
} else if(bodyid == 'pink') {
bridgeCanvas.fillStyle = "#96b6cd";
}
};
The full code is in the codepen below
https://codepen.io/oddpandadesign/pen/vYyybQG
You have to set the color first and then fill the rectangle.
bridgeCanvas.fillStyle = color;
bridgeCanvas.fillRect(0, 0, bridge.width, bridge.height);
I want to make green ellipses on left side and red ellipses on right side. I use random function to fill the canvas. I use if statements for my purpose. Maybe switch case would be better for this task?
This syntax only generate pink dots, whats wrong?
var spotPos = {
x:300,
y:200
}
var spotCol = {
r:0,
g:0,
b:0
}
function setup() {
createCanvas(600,400);
background(0);
}
function draw() {
spotPos.x = random(0,width);
spotPos.y = random(0,height);
//spotCol.r = random(60,255);
noStroke()
fill(spotCol.r, spotCol.g, spotCol.b)
ellipse(spotPos.x, spotPos.y, 25, 25);
if(spotPos.x < 300) {
spotCol.b = 255;
} else if(spotPos.x > 300) {
spotCol.r = 255;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/p5.js"></script>
There were a few things preventing you from achieving your desired result.
First you drew the ellipse and then afterwards selected a color. That meant that in the next round of the draw loop, the ellipse will be drawn somewhere else but the color will still be based on the previous position.
The second problem was the assignment of RGB values:
if(spotPos.x < 300) {
spotCol.b = 255;
} else if(spotPos.x > 300) {
spotCol.r = 255;
}
You only ever assigned blue and red a value of 255 and never changed it backed. So after a few iterations you have fill(255, 0, 255) e.g. full red, no green, full blue which resulted in the pink color you were seeing.
Think of draw as a set of instructions that you repeat over and over again. You need to consider the order of your instructions and in what state you end/start each iteration of your loop. If you change some global variables how will they affect your program the next time draw is run?
I've included a working example below but feel free to experiment with your own ideas and solutions.
const spotPos = {
x: 300,
y: 200
}
const spotCol = {
r: 0,
g: 0,
b: 0
}
function setup() {
createCanvas(600, 400);
background(0);
}
function draw() {
spotPos.x = random(0, width);
spotPos.y = random(0, height);
if (spotPos.x < 300) {
spotCol.r = 0;
spotCol.g = 255;
} else if (spotPos.x > 300) {
spotCol.r = 255;
spotCol.g = 0;
}
noStroke();
fill(spotCol.r, spotCol.g, spotCol.b)
ellipse(spotPos.x, spotPos.y, 25, 25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/p5.js"></script>
If you draw the circle first before coloring it, it won't detect the new color.
I am currently tasked with creating shapes on a canvas of different colors using a DOM. This is my first experience with the DOM. All the HTML and JS works fine if there was 1 color for all shapes, but I am trying to edit the function in question (drawShape(canvasID)) to have an if-else statement that determines the name of the canvasID and have a color associated with it.
Below is my first attempt at differentiating between two canvasId's to display either a red or blue rectangle.
function getElement(elementName) {
var element = document.getElementById(elementName);
return element;
}
function drawShape(canvasID){
var canvas = getElement(canvasID);
alert("Canvas is" + canvas);
var ctx= canvas.getContext('2d');
//ctx.rect(25, 25, 100, 100);
//ctx.fillStyle = "red";
//ctx.fill();
if (canvas == "CANVAS1"){
ctx.rect(25, 25, 100, 100);
ctx.fillStyle = "red";
ctx.fill();
}else if (canvas == "CANVAS2"){
ctx.rect(25, 25, 100, 100);
ctx.fillStyle = "blue";
ctx.fill();
}
}
As I said the rest of the program runs fine, and if I delete the if/else statements and use the lines that are currently comments, then the program will display all the rectangles as red. I just wanted advice on differentiating the colors. Any help is appreciated!
If editing to show all the JS and HTML is necessary just let me know!
Recently had almost the same problem.
Be sure to use "ctx.beginPath();" objects separator;
You can always replace a rect with a line.
See my code for changing color lines:
function lines(color1,color2) {
for (i = 0, j = 0; i <= 8 * 20; i += 20, j++) {
ct3.beginPath();
ct3.moveTo(300, 30 + i);
ct3.lineTo(900, 30 + i);
ct3.lineWidth = 20;
ct3.strokeStyle = (j%2 != 0) ? color1 : color2;
ct3.stroke();
}
}
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();
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
}
I put this maze game together for a school project with the help from a few partner. I've gotten drawing on images to work, but my teacher is looking for some form of boundary/border preventing the user from skipping past walls. I'm not even sure if it's possible.
This is the block for individual images along with a short snippet of the Level selector buttons.
Note: These are just parts of the code arranged to show you guys the part I'm talking about. It's formatted differently in the actual file.
<li align="center" style="color:yellow"><div style="color:yellow">(Medium) </div><input type="button" id="l2" value="Level 2" onClick="test2()"/>
<script>
var img2 = new Image();
function test2() {
can.width = img2.width;
can.height = img2.height;
ctx.drawImage(img2, 0, 0);
}
img2.src = 'http://www.hereandabove.com/cgi-bin/maze?30+30+20+5+5+0+0+0+255+255+255.jpg';
</script>
Here is the code I am using to allow drawing on the images.
<canvas id="can1">
<script>
var el = document.getElementById('can1');
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
isDrawing = true;
ctx.strokeStyle = "green";
ctx.lineWidth = 4;
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(e.offsetX, e.offsetY);
};
el.onmousemove = function(e) {
if (isDrawing) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
</script>
Without knowing what your maze images look like it's a little difficult, but a very rudimentary solution would be to check the color of the image at the mouse cursor point, and depending on the color decide whether to keep drawing.
I've got some mostly accurate code below, the idea is in this case to get the color of the image at the position of the mouse cursor. In this case I assume a black and white maze where the walls are black and movable area is white. I check the color data to see that red is maxed out (this will only work if your walking area is a color where red is maxed out, like white, red, or yellow. For different colors adjust accordingly, but here rgbColorData is an array where 0 is red, 1 is green, and 2 is blue). As long as the color determines it's movable, then you move.
Again, without the actual code it's hard to provide a perfect answer, but I'd go in this direction.
var rgbColorData = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data;
if (rgbColorData[0] == 255) {
isDrawing = true;
ctx.strokeStyle = "green";
ctx.lineWidth = 4;
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(e.offsetX, e.offsetY);
}