How to make "Download Background Image" button in JavaScript? - javascript

I made a random background color generator in HTML/JavaScript. Now, I want to add "Download Background Image" button. But I don't know how.
Here is my code:
function randomBgColor() {
var rmin = +rmintxt.value;
var rmax = +rmaxtxt.value;
var gmin = +gmintxt.value;
var gmax = +gmaxtxt.value;
var bmin = +bmintxt.value;
var bmax = +bmaxtxt.value;
var r = Math.floor(Math.random() * (rmax - rmin + 1) + rmin);
var g = Math.floor(Math.random() * (gmax - gmin + 1) + gmin);
var b = Math.floor(Math.random() * (bmax - bmin + 1) + bmin);
var r2 = Math.floor(Math.random() * 255);
var g2 = Math.floor(Math.random() * 255);
var b2 = Math.floor(Math.random() * 255);
var rhex = r.toString(16);
var ghex = g.toString(16);
var bhex = b.toString(16);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";
var bgColor2 = "rgb(" + r2 + "," + g2 + "," + b2 + ")";
document.body.style.background = bgColor;
rgb.innerHTML = "RGB: " + r + ", " + g + ", " + b;
rgb.style.color = bgColor2.toString(16);
hex.innerHTML = "Hex: #" + rhex.toUpperCase() + ghex.toUpperCase() + bhex.toUpperCase();
hex.style.color = bgColor2.toString(16);
}

I don't know why it doesn't work on StackOverflow, but on my computer it works well. Try to copy-paste and check it out.
var theCanva = document.querySelector('canvas');
var twoD = theCanva.getContext("2d");
var theBtn = document.querySelector('.btn');
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
twoD.width = window.innerWidth;
twoD.height = window.innerHeight;
var link = document.createElement('a');
link.innerHTML = 'Download';
link.addEventListener('click', function(ev) {
link.href = theCanva.toDataURL("image/png");
link.download = "test";
}, false);
theBtn.addEventListener('click', () => {
var color = random_rgba();
twoD.fillStyle = color;
twoD.fillRect(0, 0, 1200, 800);
document.body.appendChild(link);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
position: fixed;
width: 100%;
height: 100vh;
z-index: -1;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<button class="btn">Generate random background color</button>
<canvas></canvas>

If you would like to have the button be able to have a file selector where you could make the page's background be the selected image, then you would need to have a file input, so that you can get the image that the user would like to use as a background to be displayed. In the JS, then you will need to create a variable to get the data of what the chosen file is. Now, you will need to have a conditional that checks if there even is a picture. So you can just do this:
if (/**Over here, you must check if the file exists and it is an image.**/) {
//Over here, you would want to turn the page's background into the image.
}
But, you need to have a function, or else the whole thing will only run at the very start of the page's load. You need to add an event listener or something that checks when the file is chosen. If you don't know how to do that, then you can just search it up. Or, you could find something on Stack Overflow that relates to it. Like this:
How to check if input file is empty in jQuery
Hope this helps! If you have any further questions, please tell me. I am new on Stack Overflow, so I need to know how I can improve. Thanks!

Related

Js function working only once

I'm working on a simple javascript photo editor, and I'm stuck on this part:
var opacity = document.getElementById("opacity").value;
var contrast = document.getElementById("contrast").value;
var saturate = document.getElementById("saturate").value;
var brightness = document.getElementById("brightness").value;
var color = document.getElementById("color").value;
var sepia = document.getElementById("sepia").value;
function filter() {
document.getElementById("output").style.filter = "hue-rotate(" + color + "deg) sepia(" + sepia + "%) brightness(" + brightness * 3 + "%) saturate(" + saturate + "%) contrast(" + contrast * 2 + "%)";
}
var filters = document.getElementsByClassName("slider");
for (i = 0; i < filters.length; i++) {
filters[i].addEventListener("click", filter);
}
This function works only once. Similar function for opacity:
function opacity() {
var a = document.getElementById("opacity").value;
document.getElementById("output").style.opacity = a / 10;
}
document.getElementById("opacity").addEventListener("change", opacity);
works fine. Any ideas why? I tried doing it this way:
/*
function contrast() {
var b = document.getElementById("contrast").value;
document.getElementById("output").style.filter = "contrast(" + b * 2 + "%)";
}
document.getElementById("contrast").addEventListener("change", contrast);
function saturate() {
var c = document.getElementById("saturate").value;
document.getElementById("output").style.filter = "saturate(" + c + "%)";
}
document.getElementById("saturate").addEventListener("change", saturate);
function brightness() {
var d = document.getElementById("brightness").value;
document.getElementById("output").style.filter = "brightness(" + d * 3 + "%)";
}
document.getElementById("brightness").addEventListener("change", brightness);
function color() {
var e = document.getElementById("color").value;
document.getElementById("output").style.filter = "hue-rotate(" + e + "deg)";
}
document.getElementById("color").addEventListener("change", color);
function sepia() {
var f = document.getElementById("sepia").value;
document.getElementById("output").style.filter = "sepia(" + c + "%)";
}
document.getElementById("sepia").addEventListener("change", sepia);
/*
And everything is ok, but then I'm unable to apply multiple filters. Any help appreciated!
You have to get the value every time you click
var contrast = document.getElementById("contrast");
var saturate = document.getElementById("saturate");
var brightness = document.getElementById("brightness");
var color = document.getElementById("color");
var sepia = document.getElementById("sepia");
function filter() {
//You have to convert to number to do arithmetic
var _brightness = ~~brightness.value;
document.getElementById("output").style.filter = "hue-rotate(" + color.value + "deg) sepia(" + sepia.value + "%) brightness(" + _brightness * 3 + "%) saturate(" + saturate.value + "%) contrast(" + contrast.value * 2 + "%)";
}
and so on

Get position in javascript not working

I want to make a small game, but I have some start up problems.
When I try to get the position of track or trackCont, it always returns x: 0, y: 0. Doesn't get right position moving the DIV with:
float: right;
display: block;
and even doesn't work using:
position: absolute;
left: 100px;
Here's the code I am using:
var Player = new Array();
var trackEntity;
function getPosition(elem){
xPos = 0;
yPos = 0;
while(elem){
xPos += (elem.offsetLeft + elem.clientLeft);
yPos += (elem.offsetTop + elem.clientTop);
elem = elem.offsetParent;
}
return {x: xPos, y: yPos};
}
window.onload = function(){
trackEntity = document.getElementById("trackCont");
for (i = 0; i < 4; i += 1){
Player[i] = new Object();
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
Player[i].entity = document.getElementById("p" + i);
Player[i].entity.style.backgroundColor = "rgb("
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) +
")";
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
}
}
http://jsfiddle.net/dh8uf6Lp/
You need to supply a unit to when assigning a value to css left.
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";
If you assign a value to a css dimension or position property it will not update when no unit is given.
It seems that when getPosition(trackEntity) is called it doesn't know where it is in the DOM. This is caused by
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
This causes the browser to redraw all elements and trackEntity loses it reference.
Solution: do not insert html via innerHTML, but create the div and append it to the DOM.
Player[i].entity = document.createElement("div");
Player[i].entity.id = "p" + i;
//etc.
document.body.appendChild(Player[i].entity);
//Run position code.
http://jsfiddle.net/dh8uf6Lp/3/

Use if statement to get percentage of input?

Everything runs correctly, but I want to add a few things. At the very end of the function I want to change the height of the canvas by comparing how many you got correct out of the amount that you wanted to answer, but with a percentage. Sorry if this is difficult to understand.
JavaScript:
<script type="text/javascript">
function myFunction() {
score = 0;
questionAmount = prompt('How many question would you like to solve?');
for(i = 0; i < questionAmount; i++) {
var x = Math.floor(Math.random() * 13);
var y = Math.floor(Math.random() * 13);
question = prompt('What is ' + x + ' * ' + y + ' = ?');
if(question == null || isNaN(question)) {
break;
}
if(question == x * y) {
score++;
}
}
alert('You got ' + score + ' out of ' + questionAmount + ' correct.');
}
</script>
HTML:
<canvas id="content"></canvas>
<br />
<button onclick="myFunction()">CLICK</button>
Just create the percentage and apply it:
var correctPercent = (parseDouble(score) / parseDouble(questionAmount)) * 100;
//change the target elements style, apply above variable
document.getElementById("content").style.height = correctPercent + "%";

Dynamically adding variables to a URL

I am trying to dynamically add parts to a URL by passing variables to the URL dynamically such as in the code below. How can I get the code below to work so that the URL comes out looking like this:
http://www.test.com/test/Test_1/ato.50/[atc1.100/atc2.200/atc3.RandomNumber/atc3.RandomNumber/atc3.RandomNumber/atc4.400
where RandomNumber is a randomly generated number using Math.floor(Math.random() * 10 * 10());
(The repeat of passing a number to atc3. is intentional.)
Code:
<html>
<body>
<script>
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)];
var Yellow = 400;
var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
i = 1;
while (i < Green.length){
var tag_two[i] ='/atc3.' + Green[i];
}
var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>';
document.write(tag);
for (i = 0, i < Green.length, i++){
document.write(tag_two[i]);
}
document.write(tag_three);
</script>
</body>
</html>
Thanks!
Instead of creating the new variable , you have to concatinate the string to the existing variable :
here is the working example http://jsfiddle.net/afsar_zan/aAbD6/
sample code
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)];
var Yellow = 400;
var i = 0;
var tag = '<script language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
while (Green.length>i){
tag += '/atc3.' + Green[i];
i++;
}
tag +='/atc4.' + Yellow + ']"></s'+'cript>';
alert(tag);
I have found some problems in your code. so I have corrected them and here is you code.
<html>
<body>
<script>
var orderID = 50;
var Red = 100;
var Blue = 200;
var Green = new Array(Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10));
var Yellow = 400;
var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0];
i = 1;
var tag_two=new Array();
while (i < Green.length){
tag_two[i] ='/atc3.' + Green[i];
i++;
}
var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>';
document.write(tag);
for (i = 0; i < Green.length; i++){
document.write(tag_two[i]);
}
document.write(tag_three);
</script>
</body>
</html>
The way you adding variables to url seems to be correct. Variables can be passed by using simple concatenate operator '+'

Javascript - Hidden maths answer.

The script below generates random numbers, and calculates the answer.
The next thing is that I want to have the answer HIDDEN and place a text area there. Then you have to input an answer and when the answer is correct, it should make the answer green.
I know it is possible, but I've searched on the internet for it without success, so I'm creating a question instead.
Here's the script:
<div id="breuken"></div>
$(function () {
var number = document.getElementById("breuken");
var i = 0;
for (i = 1; i <= 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
number.innerHTML += "" + fRandom + " - " + sRandom + " = " + calc + "<br />";
}
number.innerHTML;
});
Try this http://jsfiddle.net/r4QTQ/
It does basic green color change but should be enough for you to modify and do exactly what you want.
Created this jQuery demo that might help you in the right direction, if you´re using jQuery.
var $questions = $('<div />').attr('id', 'questions');
for (var i = 1; i <= 3; i++) {
var question = "Question " + i + "?";
var answer = i;
$questions.append(
$('<div />')
.attr('id', 'question' + i)
.addClass('question')
.append(
$('<span />').text(question)
)
.append(
$('<input type="text" />')
.addClass('answer')
.data('answer', answer)
)
);
}
$('#container').empty().append($questions);
Hope it helps!
This answers does practically the same as #gillesc's but uses jQuery to do the heavy lifting, which you should use if you have it at hand. (and is shorter)
Javascript code: jsFiddle
$(function() {
var checkAnswer = function(elem) {
if ($(elem).data('calc') == $(elem).val()) {
$(elem).css('background-color', 'green');
} else {
$(elem).css('background-color', 'white');
}
};
var div = $('#breuken');
for (var i = 0; i < 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
var qa = $('<span>' + fRandom + ' - ' + sRandom +
' = <input type="text"></span><br />');
qa.find('input').change(function() {
checkAnswer(this);
}).data('calc', calc);
div.append(qa);
}
});

Categories

Resources