I'm creating a canvas drawing apps but stuck - javascript

I'm creating a canvas drawing apps but I got stuck in my code. I am new to javascript so it seems difficult for me:
var input = document.getElementById('chColor');
input.onkeyup = function() {
document.getElementById('color_check').style.background = input.value;
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown',painting,false);
function painting() {
canvas.onmousemove = function(e) {
var mouseX = e.pageX - canvas.offsetLeft;
var mouseY = e.pageY - canvas.offsetTop;
ctx.fillStyle = input.value;
ctx.fillRect(mouseX,mouseY,10,10);
}
canvas.onmouseup = function() {
canvas.onmousemove = '';
}
}
var erase = document.getElementById('clear');
erase.onclick = function() {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
body {
background: #dfdfdf;
}
.colorplate {
position: relative;
width: 100%;
height: 50px;
background: #fff;
box-shadow: 0px 0px 2px 2px rgba(0,0,0,.3);
}
#chColor {
width: 250px;
border:none;
background: none;
line-height: 50px;
font-size: 20px;
}
#chColor:focus {
outline: none;
}
::-webkit-input-placeholder {
color:#333;
}
#color_check {
position: absolute;
width: 250px;
height: 100%;
background: #fff;
box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3);
top:0;
left:50%;
}
canvas {
background: #fff;
box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3);
}
#clear {
padding: 10px;
border:none;
background-color: #fff;
box-shadow: 0px 0px 2px 2px rgba(0,0,0,0.3);
cursor: pointer;
}
#clear:hover {
background: #333;
color:#fff;
}
<div class="colorplate">
<input type="text" id="chColor" placeholder="type your color name or hex">
<div id="color_check"></div>
</div>bbb
<canvas id="canvas" width="300" height="300"></canvas>
<button id="clear">Erase all</button>
please update some code and make to much beautiful than mine. I hope you will help me for my problem.

Related

is it possible for a function to connect to another function and gather information from an array JS

is it possible to make a function that is connected to another function that has an array this is a JS game Red Light Green Light the array is holding the text "Green Light, Red Light" I want to know if its possible to make another function that is taking information from my characters movement and when the green light or red light text appears for exapmple when green light appears nothing happens because its safe to move but when red light it appears you fail and a game over screen appears
var colors = ['Green light', 'Red light'];
(function () {
var words = ["Red light"]
i = 0;
setInterval(function(){ $('#words').fadeOut(function(){
$(this).html(colors[(i = (i + 1) % colors.length)]).fadeIn();
}); }, 4000)
})();
$(document).ready(function(){
var Block = function()
{
this.goalDistance = 1370;
this.distanceTraveled = 0;
go = false;
}
var block = new Block();
$('#green-button').click(function(){
console.log('GO!');
block.go = true;
animateBlock();
// this allows the block bob to move forward
});
$('#red-button').click(function(){
console.log('STOP!');
block.go = false;
// this allows the block bob to stop moving
});
function animateBlock()
{
if(block.go === true && block.distanceTraveled < block.goalDistance)
{
$('#block').animate({left:'+=10'},50);
block.distanceTraveled += 10;
setTimeout(function(){
animateBlock();
},50);
}
}
});
canvas{
border: 1px solid black;
width: 65%;
margin-top: 35px;
margin-inline-start: 5px;
border-inline-start-color: #ffffff;
}
body {
background-color: grey;
}
.container {
width: 20%;
max-width: 20px;
margin: auto;
}
.animated-heading {
display: flex;
align-items: center;
justify-content: center;
height: 1vh;
}
h1{
color: black;
}
#finish-line
{
position:absolute;
height:650px;
width:10px;
left:1670px;
top:135px;
background-color:black;
}
.buttons
{
margin-top: 1px;
float: left;
}
.light
{
width:150px;
height:50px;
margin-left:30px;
color:white;
font-size:2em;
}
#green-button
{
background-color:green;
border-radius: 12px;
display: inline-block; margin-right: 20px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
width: 200px;
margin-left: 820px;
margin-right: 5px;
cursor: pointer
}
#red-button
{
background-color:red;
border-radius: 12px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
width: 200px;
margin: 0 auto;
margin-right: 1px;
cursor: pointer
}
.block
{
position:relative;
width:40px;
height:39px;
background-image: url('./image/bob.jpg');
border: 1px solid black;
bottom:400px;
left:310px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center><h1><span id="words"> Red light</span></h1></center>
<center><canvas id="myCanvas"></canvas></center>
<div class="container"></div>
<div class="animated-heading"></div>
<div class="block" id="block"></div>
<div id = 'finish-line'></div>
<div class="buttons">
<button class = "light" id="green-button" type="button">GO!</button>
<button class = "light" id="red-button" type="button">STOP!</button>
</div>

Sent information from backend (flask) to frontend without refreshing the page

I have an interface where I can draw a picture.
I have a machine learning model that can recognize this image.
What I want?
After clicking on the button "Recognize" I want to send the output from a machine learning model to an external interface i.e. a text field WITHOUT REFRESHING THE PAGE.
Before pressing the button "Recognize"
After pressing the button "Recognize"
With the code below I can print the output of the model to the terminal, but I need to send it to a text field.
paint.html
<html>
<head>
<meta charset="utf-8">
<title>Drawing App</title>
<link rel="stylesheet" href="static/style.css" type="text/css" media="screen" title="no title">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
</head>
<body>
<h2>Phone Number Recognition<img src="https://cdn1.iconfinder.com/data/icons/fatcow/32/painbrush.png" alt="" class="paint"></h2>
<canvas width="1024" height="256" id="mainCanvas"></canvas>
<div class="controls">
<button id="clear" onclick='clear_canvas()'>Clear</button>
<button id="recognize" onclick='recognize_number()'>Recognize</button>
<label id="label1"></label>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="static/main.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
style.css
* {
margin: 0;
padding: 0;
}
body {
background: #F5F5F5;
font-family: sans-serif;
height: 100%;
width: 100%;
}
h2 {
text-align: center;
margin: 20px;
font-family: 'Open Sans', sans-serif;
}
.paint {
padding-top: 2px;
}
/* CANVAS STYLING
===================*/
canvas {
display: block;
margin: 40px auto 10px;
border-radius: 5px;
border-left: 1px solid #E0E0E0;
border-right: 1px solid #E0E0E0;
border-top: 1px solid #E0E0E0;
box-shadow: 0 4px 0 0 #E0E0E0;
cursor: url(../img/cursor.png), crosshair;
}
.controls {
min-height: 60px;
margin: 0 auto;
width: 600px;
border-radius: 5px;
overflow: hidden;
}
ul {
list-style:none;
margin: 0;
float: left;
padding: 10px 0 20px;
width: 100%;
text-align: center;
}
/* BUTTON STYLES
==============*/
button {
background: #68B25B;
box-shadow: 0 3px 0 0 #6A845F;
color: #fff;
outline: none;
cursor: pointer;
text-shadow: 0 1px #6A845F;
display: block;
font-size: 16px;
line-height: 40px;
}
label {
background: #c7ebc1;
box-shadow: 0 3px 0 0 #6A845F;
color: rgb(0, 0, 0);
outline: none;
cursor: pointer;
text-shadow: 0 1px #6A845F;
display: block;
font-size: 16px;
line-height: 40px;
}
#clear {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 160px;
height: 40px;
}
#recognize {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 160px;
height: 40px;
}
#label1 {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 260px;
height: 40px;
}
main.js
var colour = $(".selected").css("background-color");
var $canvas = $("canvas");
var context = $canvas[0].getContext("2d");
var lastEvent;
var mouseDown = false;
context.fillStyle = "white";
context.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
// On mouse events on the canvas
$canvas.mousedown(function (e) {
lastEvent = e;
mouseDown = true;
}).mousemove(function (e) {
// Draw lines
if (mouseDown) {
context.beginPath();
context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
context.lineTo(e.offsetX, e.offsetY);
context.strokeStyle = colour;
context.lineWidth = 10;
context.lineCap = 'round';
context.stroke();
lastEvent = e;
}
}).mouseup(function () {
mouseDown = false;
}).mouseleave(function () {
$canvas.mouseup();
});
// Clear the canvas when button is clicked
function clear_canvas() {
context.fillStyle = "white";
context.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
}
function recognize_number() {
var imgURL = $canvas[0].toDataURL('image/jpg');
$.ajax({
type: "POST",
url: "http://172.28.104.162:8080/hook",
data:{
imageBase64: imgURL
}
}).done(function() {
console.log('sent');
});
}
Flask
from flask import Flask, render_template, request
import os
import base64
import re
SAVE_PATH = '../data_from_flask'
app = Flask(__name__)
def some_model(img_path):
return 'some_output'
#app.route("/")
def home():
return render_template("paint.html")
#app.route('/hook', methods=['GET', 'POST'])
def recognize_image():
image_b64 = request.values['imageBase64']
image_data = re.sub('^data:image/.+;base64,', '', image_b64)
image_path = f"{SAVE_PATH}/flask_{len(os.listdir(SAVE_PATH))}.jpg"
with open(image_path, "wb") as fh:
fh.write(base64.decodebytes(bytes(image_data, encoding='UTF-8')))
recognized_number = some_model(img_path=image_path)
print(recognized_number)
return render_template('paint.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8080', debug=False)
You can get your element by its id and set the text to your computed output.
const labelElement = document.getElementById('label1');
function recognize_number() {
var imgURL = $canvas[0].toDataURL('image/jpg');
$.ajax({
type: "POST",
url: "http://172.28.104.162:8080/hook",
data:{
imageBase64: imgURL
}
}).done(function(output) {
labelElement.innerText = output;
});
}

How do I get my etch-a-sketch program to "listen" to this dropdown menu instead of the buttons?

I'm new to Stack Overflow. I hope that I'm doing this correctly. ❤
I'm working on an old Etch-a-Sketch JavaScript project from months ago and decided to rework the 'mobile' form of the project because I hadn't bothered to do so at the time. At first, I tried just moving the buttons to the top horizontally, but I didn't like any of the variations I tried. So I decided I'd be better off with a dropdown menu instead that would appear when the screen is 500px or smaller, replacing the buttons.
The dropdown menu is supposed to do exactly what the buttons do - when a certain mode is selected, that's the mode that the program is supposed to switch to. For example, when the "Party mode" button is clicked, the program switches to "party mode". I want the dropdown menu to behave similarly - when the "party mode" option is selected, the program should switch to "party mode".
My logic was that I needed a function that grabbed the value of the dropdown menu, and then an "if" condition would run that pretty much says "If the value is x, x mode should run; else if the value is y, y mode should run", and so on. I added the function to the existing window.onload function so it would run upon the window loading. This didn't work.
Note that the dropdown menu will, in the future, only appear when the screen size is 500px or less. In addition, I still have the buttons on the screen for all sizes, just for testing/debugging purposes. When I'm done and have this figured out, the buttons will have "display = 'none'" and be hidden for the "mobile size".
Anyway, so yeah, the program is still just listening to the buttons, and not the dropdown menu. That leads me to believe that I need to somehow turn "off" the button mode? If that's the case, how do I do that? If that's not the case, what am I supposed to do here? Any help or insight would be greatly appreciated. Thanks!
const defaultMode = 'default';
const defaultSize = 30;
const defaultColor = '#0b478b';
let currentMode = defaultMode;
let currentSize = defaultSize;
let currentColor = defaultColor;
// Sets the program's current mode
function setCurrentMode(newMode) {
activeButton(newMode);
currentMode = newMode;
}
// Sets the grid's size
function setCurrentSize(newSize) {
currentSize = newSize;
}
// Sets the color of the square (if in default mode)
function setCurrentColor(newColor) {
currentColor = newColor;
}
// Links the various HTML elements to this script
const sizeValue = document.querySelector('#sizevalue');
const sizeSlider = document.querySelector('#sizeslider');
const colorPicker = document.querySelector('#colorpicker');
const defaultBtn = document.querySelector('#default');
const partyBtn = document.querySelector('#party');
const grayBtn = document.querySelector('#grayscale');
const eraserBtn = document.querySelector('#eraser');
const clearBtn = document.querySelector('#clear');
const grid = document.querySelector('#maincontainer');
// DOM manipulations for buttons, color picker, and size slider
colorPicker.onchange = (e) => setCurrentColor(e.target.value);
defaultBtn.onclick = () => setCurrentMode('default');
partyBtn.onclick = () => setCurrentMode('party');
grayBtn.onclick = () => setCurrentMode('gray');
eraserBtn.onclick = () => setCurrentMode('eraser');
clearBtn.onclick = () => reloadGrid();
sizeSlider.onmousemove = (e) => updateSizeValue(e.target.value);
sizeSlider.onchange = (e) => changeSize(e.target.value);
// When the size is changed, we set the grid size, update the size value (text), and reload the grid.
function changeSize(num) {
setCurrentSize(num);
updateSizeValue(num);
reloadGrid();
}
// When we update the size value, the text changes to reflect the value. (It's a square, so the value is always the same for length and width).
function updateSizeValue(num) {
sizeValue.innerHTML = `${num} x ${num}`;
}
// When we reload the grid (which happens when "Clear grid" is pressed), we ensure that we clear the grid and that the size is still the current size.
function reloadGrid() {
clearGrid()
makeGrid(currentSize)
}
// When we clear the grid, it clears the grid.
function clearGrid() {
grid.innerHTML = ''
}
// Creates the base grid and includes the code that says "when the mouse goes over the squares, draw."
function makeGrid(size) {
grid.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (i = 0; i < size * size; i++) {
let square = document.createElement('div');
square.addEventListener('mouseover', changeColor);
grid.appendChild(square);
}
}
// These are the conditions to set the color of the "pen" (squares)
function changeColor(e) {
if (currentMode === 'party') {
const randomR = Math.floor(Math.random() * 256);
const randomG = Math.floor(Math.random() * 256);
const randomB = Math.floor(Math.random() * 256);
e.target.style.backgroundColor = `rgb(${randomR}, ${randomG}, ${randomB})`;
} else if (currentMode === 'default') {
e.target.style.backgroundColor = currentColor;
} else if (currentMode === 'gray') {
e.target.style.backgroundColor = calculateGray(e);
} else if (currentMode === 'eraser') {
e.target.style.backgroundColor = 'white';
}
}
// Shading mode code
function calculateGray(e) {
let clr = returnRGB(e.target.style.backgroundColor);
if (!clr || clr[1] !== clr[2] || clr[1] !== clr[3]) {
return `rgb(255, 255, 255)`;
}
return clr[1] <= 0 ? `rgb(255, 255, 255)` : `rgb(${clr[1]-25}, ${clr[1]-25}, ${clr[1]-25})`;
}
function returnRGB(num) {
return num.match(/rgb\(([0-9]*), ([0-9]*), ([0-9]*)\)/);
}
// Changes the button styling to indicate which mode is the active mode
function activeButton(newMode) {
if (currentMode === 'party') {
partyBtn.classList.remove('active');
} else if (currentMode === 'default') {
defaultBtn.classList.remove('active');
} else if (currentMode === 'gray') {
grayBtn.classList.remove('active');
} else if (currentMode === 'eraser') {
eraserBtn.classList.remove('active');
}
if (newMode === 'party') {
partyBtn.classList.add('active');
} else if (newMode === 'default') {
defaultBtn.classList.add('active');
} else if (newMode === 'gray') {
grayBtn.classList.add('active');
} else if (newMode === 'eraser') {
eraserBtn.classList.add('active');
}
}
// Ensures that, when we load the page, we make the grid and activate the correct mode (default).
window.onload = () => {
makeGrid(defaultSize);
activeButton(defaultMode);
dropdownModeThing(document.getElementById('dropdown-mode').value);
}
// Code for the dropdown menu
function dropdownModeThing(val) {
if (val === 'default') {
setCurrentMode('default');
} else if (val === 'party') {
setCurrentMode('party');
} else if (val === 'shading') {
setCurrentMode('gray');
} else if (val === 'eraser') {
setCurrentMode('eraser');
} else if (val === 'clear') {
reloadGrid();
}
}
body,
html {
min-height: 100vh;
height: 100%;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 0;
padding: 0;
background-color: white;
overflow-x: hidden;
}
header {
text-align: center;
margin: 0;
border-bottom: 1px solid black;
background-color: #0b478b;
color: white;
padding: 10px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
p {
margin: 0;
}
h1 {
text-align: center;
margin: 0;
font-size: 2.5rem;
padding: 0;
}
#maincontainer {
background-color: white;
margin: 20px auto 10px auto;
display: grid;
border: 1px solid black;
width: 45vw;
height: 45vw;
min-height: 300px;
min-width: 300px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
.testing {
padding-top: 100%;
color: hsla(0, 0%, 68%, 0.596);
}
#btncontainer {
padding-top: 20px;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
a {
color: #2aa5a1;
text-decoration: none;
}
a:hover {
color: white;
}
button {
background-color: #2aa5a1;
color: white;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: 1px solid black;
margin: 10px 15px;
padding: 8px 10px;
font-size: .9em;
transition: 0.3s;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
button:active {
background-color: #3F86D8;
color: white;
border: 1px solid black;
}
.active {
background-color: #3F86D8;
transition: 0.3s;
color: white;
border: 1px solid black;
}
button:hover {
background-color: #0b478b;
color: white;
border: 1px solid black;
opacity: 1;
}
#rightside {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
text-align: center;
min-height: 500px;
padding: 0;
margin: 0;
}
#sizevalue {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin-bottom: 0;
}
input[type=range] {
background-color: white;
height: 28px;
-webkit-appearance: none;
margin: 0;
margin-bottom: 35px;
width: 250px;
padding: 0;
}
input[type=range]:focus {}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #FFFFFF;
cursor: pointer;
-webkit-appearance: none;
margin-top: -5px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #3F86D8;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-fill-upper {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-thumb {
margin-top: 1px;
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]:focus::-ms-fill-lower {
background: #3F86D8;
}
input[type=range]:focus::-ms-fill-upper {
background: #3F86D8;
}
main {
display: flex;
justify-content: center;
margin: 0;
margin-bottom: 20px;
padding: 0;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100vw;
width: 50px;
height: 50px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
input[type='color']:hover {
transform: scale(1.05);
}
input[type='color']::-webkit-color-swatch-wrapper {
padding: 0;
}
input[type='color']::-webkit-color-swatch {
border: none;
border-radius: 50px;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
/* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 50%;
right: 100%;
/* To the left of the tooltip */
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent black transparent transparent;
}
footer {
color: white;
text-align: center;
background-color: #0b478b;
position: fixed;
bottom: 0;
width: 100%;
margin: 0;
padding-top: 10px;
padding-bottom: 15px;
}
#media (max-width: 500px) {
main {
flex-direction: column;
}
#btncontainer {
margin: 0 auto;
padding: 20px 10px 5px 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
}
#btncontainer button {
margin: 0 3px;
height: 35px;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100px;
width: 35px;
height: 35px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CSS spreadsheet -->
<link href="styles.css" rel="stylesheet">
<title>Etch-a-Sketch</title>
</head>
<body>
<!-- Note that this is set up in various divs so
that we can use Flex to create our wanted layout. -->
<div id="entirepage">
<header>
<h1>Etch-a-Sketch</h1>
<p title="Testing">Select a color or a different mode, then select your size, and get drawing!</p>
</header>
<main>
<div id="btncontainer">
<select id="dropdown-mode">
<option value="default">Default mode</option>
<option value="party">Party mode</option>
<option value="shading">Shading</option>
<option value="eraser">Eraser mode</option>
<option value="clear">Clear grid</option>
</select>
<input type="color" id="colorpicker" value="#0b478b">
<button id="default">Default mode</button>
<button id="party">Party mode</button>
<button id="grayscale">Shading</button>
<button id="eraser">Eraser mode</button>
<button id="clear">Clear grid</button>
</div>
<div id="rightside">
<div id="maincontainer">
</div>
<label for="sizeslider" id="sizevalue">30 x 30</label>
<input type="range" min="1" max="100" value="30" id="sizeslider">
</div>
</main>
<footer>
<p>Created by Sara Dunlop (RiscloverYT)</p>
</footer>
</div>
<!-- JavaScript script -->
<script src="script.js"></script>
</body>
</html>
Luckily, there's an easy way to do that. Add this piece of code into your javascript file and see the magic.
const dropdown = document.getElementById('dropdown-mode');
dropdown.addEventListener('change', (e) => {
setCurrentMode(e.target.value);
});
Read more about change event here.

Transition from right to left

I need to change some background color with a smooth transition from right to left instead of just changing the color in a uniform way. I will now provide you my code, so that maybe it will be more clear.
NO jQuery/libraries allowed
HTML
<div id=astuccio>
<div class="cBox" id="cBox1">
<div class="color" id="color1"></div>
</div>
<div class="cBox" id="cBox2">
<div class="color" id="color2"></div>
</div>
<div class="cBox" id="cBox3">
<div class="color" id="color3"></div>
</div>
</div>
<button class="js" id="roll">⋁</button>
CSS
#astuccio {
grid-row: 1/2;
margin: auto;
}
.cBox {
width: 50px;
height: 50px;
display:inline-block;
margin: auto;
border-radius: 5px 5px 5px 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
-webkit-box-shadow: inset 0px 0px 10px 0px rgba(0,0,0,0.3);
-moz-box-shadow: inset 0px 0px 10px 0px rgba(0,0,0,0.3);
box-shadow: inset 0px 0px 10px 0px rgba(0,0,0,0.3);
border: 0.5px solid rgb(175,175,175);
box-sizing: content-box;
transition: 0.5s;
}
#cBox1 {
margin: auto 0px auto auto;
}
#cBox2 {
width: 100px;
height: 100px;
}
#cBox3 {
margin: auto auto auto 0;
}
.color{
width: 40px;
height: 40px;
vertical-align: middle;
margin-left: 5px;
margin-top: 5px;
text-align: center;
position: relative;
background: tomato;
display: inline-block;
border: 1px solid black;
z-index: 10;
transition: 0.5s linear;
transform-origin: left;
}
#color1 {
background: pink;
}
#color2 {
width: 90px;
height: 90px;
background: pink;
transition-delay: 0.2s;
}
#color3 {
background: pink;
transition-delay: 0.4s;
}
#roll {
grid-row: 2/3;
width: 45px;
height: 45px;
margin: auto;
cursor: pointer;
border-radius: 500px 500px 500px 500px;
-moz-border-radius: 500px 500px 500px 500px;
-webkit-border-radius: 500px 500px 500px 500px;
border: 1px solid rgba(0,0,0,0.5);
box-sizing: border-box;
line-height: 45px;
text-align: center;
font-weight: lighter;
font-size: 1.2em;
color: rgba(0,0,0,0.9);
background: transparent;
}
Javascript
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function gestoreGiro () {
bott.disabled= true;
bott.setAttribute("style", "background:gray")
t = setInterval(scorri, 500);
setTimeout(riattiva, 5000);
}
function riattiva() {
document.getElementById('roll').disabled = false;
bott.setAttribute("style", "background:none");
}
function scorri() {
var n = i - 1;
var lunghezza = listaColori["colori"].length;
const valore = getRandomInt(listaColori["colori"].length);
if (i>listaColori["colori"].length-1) {
i = 0;
}
if (n < 0) {
n = lunghezza-1;
}
if (m>listaColori["colori"].length-1) {
m = 0;
}
S1.setAttribute("style","background:"+listaColori["coloriHEX"][n]);
S2.setAttribute("style","background:"+listaColori["coloriHEX"][i]);
S3.setAttribute("style","background:"+listaColori["coloriHEX"][m]);
i++;
m++;
flag++;
if (flag==13) {
clearInterval(t);
n = valore-1;
m = valore +1;
if (n < 0) {
n = lunghezza-1;
}
if (m>lunghezza-1) {
m = 0;
}
S1.setAttribute("style","background:"+listaColori["coloriHEX"][n]);
S2.setAttribute("style","background:"+listaColori["coloriHEX"][valore]);
S3.setAttribute("style","background:"+listaColori["coloriHEX"][m]);
flag = 0;
}
}
var S1 ;
var S2 ;
var S3 ;
var bott;
var i = 0;
var m = i+1;
var t;
var flag = 0;
function gestoreLoad () {
S1 = document.getElementById("color1") ;
S2 = document.getElementById("color2") ;
S3 = document.getElementById("color3") ;
bott = document.getElementById("roll");
bott.onclick = gestoreGiro;
}
window.onload = gestoreLoad;
var listaColori = {
colori: ["verde", "giallo", "rosso", "blu", "nero", "bianco"],
coloriHEX: ["#2e8b57", "#ffd700", "#ff6347", "#4169e1", "#000000", "#ffffff"]
}
I am sorry if my explanation appears poor: I'll be happy to answer your doubts.
You could do it very simply with css transition. This method work on :hover. Working CodePen.
HTML
<div>
<p>This is some text</p>
</div>
CSS
div {
padding: 20px;
width: 100px;
background: linear-gradient( to left, red 50%, blue 50% );
background-size: 200% 100%;
background-position: right bottom;
transition: all ease 1s;
color: white;
}
div:hover {
background-position: left bottom;
}

Open a popup window in the center of the monitor

I am trying to open a popup window in the center of the monitor. As I know screen size of each desktop or laptop will vary. So that is the reason I am looking for some way so that whenever my code tries to open a popup window it should get opened in the center of the browser.
Below is my code-
<html>
<head>
<style>
* { font-family: Trebuchet MS; }
#containerdiv {width:90%; height: 90%; display: none; position: fixed;margin-top: 5%; margin-left: 5%; background:#FFF; border: 1px solid #666;border: 1px solid #555;box-shadow: 2px 2px 40px #222; z-index: 999999;}
/*#containerdiv iframe {display:none; width: 100%; height: 100%; position: absolute; border: none; }*/
#blockdiv {background: #000; opacity:0.6; position: fixed; width: 100%; height: 100%; top:0; left:0; display:none;}
ul { padding:10px; background: #EEE; position: absolute; height: 200px; overflow: scroll;}
ul li {color: #222; padding: 10px; font-size: 22px; border-bottom: 1px solid #CCC; }
h3 { font-size: 26px; padding:18px; border-bottom: 1px solid #CCC; }
#close { top: 13px;position: absolute;right: 13px; padding: 10px; background: #EEE; border: 1px solid #CCC;}
#close:hover { cursor: pointer; background: #E5E5E5 }
#apply { top: 13px;position: absolute;left: 13px; padding: 10px; background: #EEE; border: 1px solid #CCC;}
#apply:hover { cursor: pointer; background: #E5E5E5 }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
function open(url) {
$('#blockdiv').fadeIn();
$('#iframe').attr('src', url);
$('#containerdiv').fadeIn();
}
function close() {
$('#blockdiv').fadeOut();
$('#containerdiv').fadeOut();
}
$(document).ready(function() {
$('ul').css({width: $('#containerdiv').width()-20,height: $('#containerdiv').height()-90})
$('#close').click( function() { close() })
$('#apply').click( function() { open('http://www.google.com/') })
});
</script>
</head>
<body>
<span id="apply">ApplyOnline</span>
<div id="blockdiv"></div>
<div id="containerdiv">
<iframe id="iframe" style="width:100%; height: 100%; outline: 1px solid red;"></iframe>
<span id="close">Close</span>
</div>
</body>
</html>
But somehow the above code, doesn't gets opened in the center of the monitor. Can anybody help me on this? What changes I need to make in the above code so that it always open the popup window in the center of the circle.
you can center you popup in css like
this is only css method to make it center so no js will be required to center it
#containerdiv {
width:90%;
height: 90%;
display: none;
position: fixed;
left:50%;
top:50%;
margin:-45% 0 0 -45%;
background:#FFF;
border: 1px solid #666;
border: 1px solid #555;
box-shadow: 2px 2px 40px #222;
z-index: 999999;
box-sizing:border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
}
It appears centered within the browser window to me.
If you want to center it based on screen resolution of the client's monitor you can use:
var centerDiv=function(){
var popUpHeight=$('#containerdiv').height();
var popUpWidth=$('#containerdiv').width();
var yPos=(window.screen.availHeight/2)-(popUpHeight/2)-window.screenY-(window.outerHeight-window.innerHeight);
var xPos=(window.screen.availWidth/2)-(popUpWidth/2)-window.screenX-(window.outerWidth-window.innerWidth);
$('#containerdiv').css({position:"absolute",top: yPos+"px",left: xPos+"px"});
}
window.onload=centerDiv();
var lastX = window.screenX;
var lastY = window.screenY;
var lastHeight = window.innerHeight;
var lastWidth = window.innerWidth;
setInterval(function(){
if(lastX != window.screenX || lastY != window.screenY || lastHeight != window.outerHeight || lastWidth != window.outerWidth){
centerDiv();
}
oldX = window.screenX;
oldY = window.screenY;
}, 33);

Categories