Change canvas fill color on button click - javascript

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);

Related

Live preview for HTML5 Canvas background and color

How do I change the background and text color with live preview for HTML5 canvas?
The code I have given on [JSFiddle][1] changes the background and text color only after the color palette is closed. I also want a variable font-family and font-size for the text on canvas. I could not find a solution anywhere.
If the code cannot be run, please solve the problem by creating an html file.
Please have a look at this [image][2] for more information.
Any suggestions and help would be appreciated.
[1]: https://jsfiddle.net/p0z1vau3/
[2]: https://i.stack.imgur.com/ZpETT.png
[3]: Source: https://codepen.io/stefan0uh/pen/QzJVxa
In your code change the eventListener to:
color.addEventListener("input", render);
bgcolor.addEventListener("input", render);
You can read more info about color picker here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color
if you need how to code the change of font size and font family use the below code. it also include answer to both questions. replace your javascript code with this.
const color = document.getElementById("color");
const canvas = document.getElementById("canvas");
const style = document.getElementById("font-family");
const size = document.getElementById("font-size");
const ctx = canvas.getContext("2d");
// onload
window.onload = () => {
render();
};
// Eventlistner
color.addEventListener("input", render);
bgcolor.addEventListener("input", render);
style.addEventListener("change", render);
size.addEventListener("change", render);
// text positions
function render() {
drawBackground();
drawText("top", canvas.height - 48,size.value,style.value);
drawText("bottom", canvas.height - 18);
}
// Need live preview for background color
function drawBackground() {
ctx.fillStyle = bgcolor.value;
ctx.fillRect(0, canvas.height - 80, canvas.width + 10, 150);
ctx.restore();
}
function drawText(text, position, fontSize, fontStyle) {
ctx.fillStyle = "#ffffff";
ctx.font = fontSize+"px "+ fontStyle; // Need variable font-family & size
// Need live preview for color
var top = [{
text: ` Text`, font: `lighter ${ctx.font}`, fillStyle: color.value}];
var bottom = [{
text: `......Text`,
font: `lighter ${ctx.font}`,
fillStyle: color.value }];
fillMixedText(ctx, text === "top" ? top : bottom, 20, position);//text positioning
}
// fillStyle
function fillMixedText(ctx, args, x, y) {
let defaultFillStyle = ctx.fillStyle;
let defaultFont = ctx.font;
args.forEach(({ text, fillStyle, font }) => {
ctx.fillStyle = fillStyle || defaultFillStyle;
ctx.font = font || defaultFont;
ctx.fillText(text, x, y);
x += ctx.measureText(text).width;
});
ctx.restore();
}

Changing boolean values using eventListener

I am trying to create an etch-a-sketch project. I have a function that paints squares black if "black variable" is true. Moreover, I have another function(it is a button on click effect function) which is capable of turning "black variable" into false and painting squares with random generated colours. However, I cannot create a button which turns "black variable" into true. BlackButton function doesn't work even though tileRainbow function works. Only the last function doesn't work.
I tried altering the function, change the order of functions.
const tiles = document.getElementsByClassName("newDiv")
let black = true
//paint squares black on mouseover effect if black is true
function tileBlack() {
if (black == true) {
for (tile of tiles) {
tile.addEventListener("mouseover", function (event) {
event.target.style.backgroundColor = "black";
})
}
}
}
//make rainbow button capable of changing black variable to false. if it is false paint squares with random generated colours.
function rainbowTile() {
black = false;
const rainbow = document.querySelector("#rainbow")
rainbow.addEventListener('click', event => {
if (black !== true) {
for (tile of tiles) {
let randomnum = Math.floor(Math.random() * 255)
let randomnum2 = Math.floor(Math.random() * 255)
let randomnum3 = Math.floor(Math.random() * 255)
tile.addEventListener("mouseover", function (event) {
event.target.style.backgroundColor = `rgb(${randomnum}, ${randomnum2}, ${randomnum3})`;
})
}
}
})
}
//make black button capable of changing black variable to true so tileBlack function activates.
function blackButton() {
const paintitblack = document.querySelector("#black")
paintitblack.addEventListener('click', event => {
black = true;
})
}
I do not get any error on console. However, my code doesn't work.
You shouldn't be testing the variable when calling addEventListener(). If you call both tileBlack() and rainbowTile(), the tiles have both event listeners.
Instead, you should add a single event listener once, and it should check the variable when it runs.
Array.from(tiles).forEach(tile => tile.addEventListener("mouseover", event => {
if (black) {
event.target.style.backgroundColor = "black";
} else {
let randomnum = Math.floor(Math.random() * 255)
let randomnum2 = Math.floor(Math.random() * 255)
let randomnum3 = Math.floor(Math.random() * 255)
tile.addEventListener("mouseover", function(event) {
event.target.style.backgroundColor = `rgb(${randomnum}, ${randomnum2}, ${randomnum3})`;
})
}
}););

Making an If-Else Statement to Choose Color of a Shape in a Canvas

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();
}
}

HTML5 Canvas - Why the color of the rectangle always returns black?

I want to draw a canvas rectangle that changes color every load. Here is my code:
window.onload = function() {
var can = document.getElementById("lol");
var ctx = can.getContext("2d");
var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"];
ctx.fillStyle = colors[Math.random() * 3];
ctx.fillRect(40,40,30,25);
}
Yet, every time when i open a web page, The color should changed to either red, blue or green but the color is persistently black.
Why is this happens? What is wrong in my code?
You're not picking the random number correctly. Your random function will hardly ever return an integer.
Read more about Math.random here.
Here is what you're trying to do:
var can = document.getElementById("lol");
var ctx = can.getContext("2d");
var colors = ["rgba(255,0,0,1)", "rgba(0,255,0,1)", "rgba(0,0,255,1)"];
ctx.fillStyle = colors[Math.floor(Math.random() * 3)];
ctx.fillRect(40,40,30,25);
<canvas id="lol"></canvas>
You need to take an integer value for accessing an array element.
ctx.fillStyle = colors[Math.floor(Math.random() * 3)];
I suggest to use the length of the array as factor for the random number (a constant vaue may go wrong if the count of elements changes later).
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
Try this: ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
https://jsfiddle.net/xpavwkod/

Javascript math.random() in a loop with canvas

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.

Categories