I am trying to use this code to resize images and print them on an html canvas to modify them later:
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, 0, 0);
However, this does not change the result on canvas. It still appears to be too large for the canvas.
When I use this code, as suggested in this question the image does not load at all. I don't know if I am using it wrong or something but it just doesn't work.
ctx.drawImage(img, 0, 0, 300, 300 * wth);
This is my code:
function preview_image(event)
{
var output = document.getElementById('output_image');
var reader = new FileReader();
var ctx = output.getContext('2d');
//output.src = "/loading.gif";
reader.onload = function()
{
//output.src = reader.result;
var img = new Image(); // Create new img element
img.src = reader.result; // Set source path
img.onload = function() {
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, 0, 0);
}
}
reader.readAsDataURL(event.target.files[0]);
}
body
{
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#0B3861;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
margin: auto;
}
#output_image
{
margin: auto;
max-width:300px;
}
.editarea{
width: 50%;
background: #EC6C67;
margin: auto;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReturNull Photo Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrapper">
<input type="file" accept="image/*" onchange="preview_image(event)"><br><br>
<div class="editarea"> <!--<img id="output_image" width="250">--> <canvas id="output_image" width="250"></canvas></div>
</div>
</body>
</html>
I changed arguments in ctx.drawImage function:
function preview_image(event)
{
var output = document.getElementById('output_image');
var reader = new FileReader();
var ctx = output.getContext('2d');
//output.src = "/loading.gif";
reader.onload = function()
{
//output.src = reader.result;
var img = new Image(); // Create new img element
img.src = reader.result; // Set source path
img.onload = function() {
var wth = img.clientHeight / img.clientWidth;
img.width=300;
img.height=300 * wth;
ctx.drawImage(img, (output.width / 2) - (img.width / 2), 0, img.width, output.height);
}
}
reader.readAsDataURL(event.target.files[0]);
}
body
{
width:100%;
margin:0 auto;
padding:0px;
font-family:helvetica;
background-color:#0B3861;
}
#wrapper
{
text-align:center;
margin:0 auto;
padding:0px;
width:995px;
margin: auto;
}
#output_image
{
margin: auto;
max-width:300px;
}
.editarea{
width: 50%;
background: #EC6C67;
margin: auto;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReturNull Photo Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrapper">
<input type="file" accept="image/*" onchange="preview_image(event)"><br><br>
<div class="editarea"> <!--<img id="output_image" width="250">--> <canvas id="output_image" width="250"></canvas></div>
</div>
</body>
</html>
Related
I have created some javascript div, a, img elements.
Making my website easier to read instead of spamming the same stuff over and over again.
My problem right now is -->
I need to use href and src links from my array ("src") and add them to my created imgages and links.
So far i have found only one working way to do it with Math...() but i don't want to show the images in random order i want them to be in the order that i have putted them in the array.
This is my code down below i will be happy if anyone helps me out!
I think this can be solved with forEach but i can't figure it out...
var src = ["https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80" ,
"https://images.unsplash.com/photo-1458966480358-a0ac42de0a7a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"];
(function () {
function createDiv() {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox"
link.appendChild(img);
link.href = src[0];
img.className ="img-fluid image scale-on-hover"
img.src = src[Math.floor(Math.random() * src.length)];
return boardDiv;
}
function createAndModifyDivs() {
var board = document.getElementById("image-builder"),
myDivs = [],
i = 0,
numOfDivs = src.length;
for (i; i < numOfDivs; i += 1) {
myDivs.push(createDiv());
board.appendChild(myDivs[i]);
}
}
createAndModifyDivs();
}());
.gallery-block.grid-gallery{
padding-bottom: 60px;
padding-top: 60px;
}
.gallery-block.grid-gallery .heading{
margin-bottom: 50px;
text-align: center;
}
.gallery-block.grid-gallery .heading h2{
font-weight: bold;
font-size: 1.4rem;
text-transform: uppercase;
}
.gallery-block.grid-gallery a:hover{
opacity: 0.8;
}
.gallery-block.grid-gallery .item img{
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.15);
transition: 0.4s;
}
.gallery-block.grid-gallery .item{
margin-bottom: 20px;
}
#media (min-width: 576px) {
.gallery-block.grid-gallery .scale-on-hover:hover{
transform: scale(1.05);
box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.15) !important;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css" />
</head>
<body>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Alexis</h3>
</div>
<div class="row" id="image-builder">
</div>
</div>
</section>
<div id="board">
</div>
</div>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>
<script>
baguetteBox.run('.grid-gallery', { animation: 'slideIn' });
</script>
</body>
</html>
You can change your createDiv() function to take in the img src as a parameter and then set it in your for loop. Your code could be cleaned up a bit and I can help with that if you leave a comment but for now I just wanted to answer your initial question.
var src = ["https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80" ,
"https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80"];
(function () {
// Take the image link as a parameter called imgSrc
function createDiv(imgSrc) {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox"
img.className ="img-fluid image scale-on-hover"
link.appendChild(img);
// Assuming here you want to link to the image
link.href = imgSrc;
// Set the img src
img.src = imgSrc;
return boardDiv;
}
function createAndModifyDivs(elmId) {
const board = document.getElementById(elmId);
for (const imgSrc of src) {
board.appendChild(createDiv(imgSrc));
}
}
const galleries = ['image-builder', 'image-builder-2'];
for(const gallery of galleries) {
createAndModifyDivs(gallery);
baguetteBox.run(`#${gallery}`);
}
}());
.gallery-block.grid-gallery{
padding-bottom: 60px;
padding-top: 60px;
}
.gallery-block.grid-gallery .heading{
margin-bottom: 50px;
text-align: center;
}
.gallery-block.grid-gallery .heading h2{
font-weight: bold;
font-size: 1.4rem;
text-transform: uppercase;
}
.gallery-block.grid-gallery a:hover{
opacity: 0.8;
}
.gallery-block.grid-gallery .item img{
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.15);
transition: 0.4s;
}
.gallery-block.grid-gallery .item{
margin-bottom: 20px;
}
#media (min-width: 576px) {
.gallery-block.grid-gallery .scale-on-hover:hover{
transform: scale(1.05);
box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.15) !important;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css" />
</head>
<body>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Alexis</h3>
</div>
<div class="gallery" id="image-builder">
</div>
</div>
</section>
<section class="gallery-block grid-gallery">
<div class="container">
<div class="heading">
<h3>Other</h3>
</div>
<div class="gallery" id="image-builder-2">
</div>
</div>
</section>
<div id="board">
</div>
</div>
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>
<script>
</script>
</body>
</html>
You only have to make these two changes, now you will pass the src as a parameter of createDiv() (look for the comments)
In App.js
var src = [
"https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1176&q=80",
"https://images.unsplash.com/photo-1458966480358-a0ac42de0a7a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
];
(function () {
//ADD A PARAMETER TO THE FUNCTION HERE
function createDiv(img_src) {
var boardDiv = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
boardDiv.className = "col-md-6 col-lg-4 item";
boardDiv.appendChild(link);
link.className = "lightbox";
link.appendChild(img);
link.href = src[0];
img.className = "img-fluid image scale-on-hover";
img.src = img_src;
return boardDiv;
}
function createAndModifyDivs() {
var board = document.getElementById("image-builder"),
myDivs = [],
i = 0,
numOfDivs = src.length;
for (i; i < numOfDivs; i += 1) {
//PASS THE SRC OF THE DIRECT IMAGE AS PARAMETER HERE
myDivs.push(createDiv(src[i]));
board.appendChild(myDivs[i]);
}
}
createAndModifyDivs();
})();
I've recently stared coding a js/html canvas file and I've noticed a big problem that I cannot solve. The problem is that the LiverSever extension suddenly stopped working. What I mean by this is out of random it just stopped working. When I try to open it, it opens in the browser but keeps on loading. I have tried many fixes but none of them seem to work. The html port "link" is," http://127.0.0.1:49423/index.html" So I was wondering if I could get some help?
html code below:
<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">
<title>Canvas</title>
<style>
canvas {
border: 1px solid lightyellow;
background: lightyellow;
}
body {
margin: 0;
}
.tooltip {
width: 100px;
position: absolute;
top: auto;
bottom: 800px;
right: 887px;
left: auto;
font-size: xx-large;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="Main_Game.js">
</script>
<div class="tooltip">Money:
<script type="text/javascript">document.write(Moneys)</script>
</div>
</body>
</html>
js code:
var canvas = document.querySelector('canvas');
canvas.width = 1920;
canvas.height = 1080;
var middlex = canvas.width/2;
console.log(middlex + " - x");
var middley = canvas.height/2;
console.log(middley + " - y");
console.log(canvas);
var c = canvas.getContext('2d');
c.fillStyle = 'rgba(255,0,0)';
c.fillRect(25,540,940,250);
c.fillRect(25, 815, 940,250);
c.fillRect(985,540,915,250);
c.fillRect(985,815,915,250);
c.beginPath();
c.arc(200, 200, 30, 0, Math.PI*2, false);
c.strokeStyle = 'blue';
c.stroke();
var Moneys = 0;
while (true) {
Moneys += 1;
}
I do not know how to delete. I figured out that the name for the html was not the same as the js file
Is it possible to add through jquery or javascript an input field in a custom position above the <canvas> element?
I have tried the following:
changing the z-index of the canvas- and input-field
putting the canvas in an div with relative property and the input-field inside a div with absolute position, but then there are those ugly scrollbar, which I do not really want there.
My index.html page looks like this:
<!DOCTYPE html>
<html manifest="cache.manifest">
<head>
<title>WebApp</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="viewport" content="width=device-width,minimum-scale=1, maximum-scale=1" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<script type="text/javascript" src="/ext/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="/ext/jquery.i18n.js"></script>
<script type="text/javascript" src="/ext/jquery.ajaxmanager.js"></script>
<script type="text/javascript" src="/ext/jquery.model.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js"></script>
</head>
<body>
<noscript>
<div style="text-align: center; width: 100%; visibility: visible;">
JavaScript ist in Ihrem Browser deaktiviert. Bitte aktivieren Sie es um diese Applikation zu starten.
<p>
JavaScript é disattivato nel Suo browser. Si prega di attivarlo per usare questa applicazione.
<p>
JavaScript is disabled in your browser. Please enable it to use this application.
<p>
How to?
</div>
</noscript>
<canvas id="app" width="150" height="30"></canvas>
</body>
</html>
Through javascript I am adding other canvas:
//This is the main canvas
this.canvas.style.zIndex = 6;
this.canvas.style.position = "absolute";
this.canvas.style.border = "0px solid";
this.canvas.style.top = 0 + "px";
this.canvas.style.left = 0 + "px";
//Some other canvas elements
var show_canvas = document.createElement('canvas');
$(this.canvas).parent().append(show_canvas);
show_canvas.style.zIndex = 4;
var other_canvas = document.createElement('canvas');
$(this.canvas).parent().append(show_canvas);
other_canvas.style.zIndex = 0;
var another_canvas = document.createElement('canvas');
$(this.canvas).parent().append(show_canvas);
another_canvas.style.zIndex = 3;
another_canvas.attr('id', 'another_canvas');
var container = document.createElement('div');
$(container).attr('id', 'input_container');
$('#another_canvas').append(container);
var user = document.createElement('input');
var pass = document.createElement('input');
$(user).attr('id', 'username');
$(pass).attr('id', 'password');
$(container).append(user);
$(container).append(pass);
$('#input_container').css({
'position': 'absolute',
'z-index': '100'
});
Currently it is looking like this:
It would be awesome, if some of you could help me solve my problem XD.
Putting the canvas and the input in a div with the div having "position: relative;" and the children having "position: absolute;" is the solution. If you want no scrollbars then either make sure the stuff inside the div is smaller than the div OR set "overflow: hidden".
One thing extra, set the canvas display type to "block". Without that the canvas is type "span" which adds space and causes a scrollbar to appear if the canvas is set to be 100%
const ctx = document.querySelector('#c1').getContext('2d');
const {width, height} = ctx.canvas;
ctx.fillStyle = "#0FF";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = "#F00";
ctx.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, Math.PI * 2, true);
ctx.fill();
body {
margin: 0;
}
#container {
position: relative;
width: 100vw;
height: 100vh;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
#form {
position: absolute;
left: 1em;
top: 1em;
padding: 0.5em;
background-color: rgba(0, 0, 0, 0.7);
}
#form input {
font-size: 20pt;
display: block;
border: none;
color: white;
background-color: #444;
margin: 0.5em;
}
<div id="container">
<canvas id="c1"></canvas>
<div id="form">
<input type="text" id="user" placeholder="username">
<input type="password" id="pass" placeholder="password">
</div>
</div>
you had your canvas 150x30? That's pretty small but we can adjust the sizes
const ctx = document.querySelector('#c1').getContext('2d');
const {width, height} = ctx.canvas;
ctx.fillStyle = "#0FF";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = "#F00";
ctx.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, Math.PI * 2, true);
ctx.fill();
#container {
position: relative;
width: 150px;
height: 30px;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
#form {
position: absolute;
left: 0;
top: 0;
background-color: rgba(0,0,0,0);
}
#form input {
font-size: 8px;
display: block;
background-color: rgba(0,0,0,0);
border: 1px solid gray;
}
<div id="container">
<canvas id="c1"></canvas>
<div id="form">
<input type="text" id="user" placeholder="username">
<input type="password" id="pass" placeholder="password">
</div>
</div>
I am using basic html input file uploader to upload image file, and div 'editor-image-1' that is preview of uploaded image. I am trying to handle this image previes with following code, but div does not change its background. Console log 'success' is being triggered, but image is not being displayed:
$("#editor-upload-1").change(function() {
$('#editor-image-1').css('background', "#FFF");
var file = this.files[0];
var imagefile = file.type;
var valid = ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
$('#editor-image-1').css('background', "#F00");
alert("Wrong image format");
return false;
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
console.log("success");
$('#editor-image-1').css('background', 'url("' + e.target.result + '")');
};
This works fine
There may be lot of failure
plz refer below code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>functionality</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<style>
.wrapper {
width: 100%;
/* whatever width you want */
display: inline-block;
position: relative;
background-size: contain;
margin: 0 auto;
}
.wrapper:after {
padding-top: 75%;
/* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
color: black;
text-align: center;
margin-top: 5%;
}
</style>
<input type="file" id="editor-upload-1">
<div class="wrapper">
<div class="main" id="main">
</div>
</div>
<script>
$(function(){
$("#editor-upload-1").change(function() {
$('#main').css('background', "#FFF");
var file = this.files[0];
var imagefile = file.type;
var valid = ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==valid[0]) || (imagefile==valid[1]) || (imagefile==valid[2]))) {
$('#main').css('background', "#F00");
alert("Wrong image format");
return false;
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
console.log("success");
$('#main').css('background', 'url("' + e.target.result + '")');
$('#main').css('top center no-repeat;');
};
</script>
</body>
</html>
This is my code for showing a image from user local machine, but it sometimes doesn't work for the first time. Specially when (on mobile) user take a picture from camera.
It almost always doesn't work for the first time that user select his image.
I use Image() to get the width and height of image for aspectRatio of resizable.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.select-img {
width: 450px;
height: 250px;
border-radius: 10px;
cursor: pointer;
border: 3px dashed gray;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
font-size: 25px;
}
#image {
display: none;
}
</style>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div class="select-img">
<p>Select Image</p>
</div>
<img id="image">
<script>
function upload (file) {
var fr = new FileReader();
fr.onload = function (event) {
var src = event.target.result;
var img = new Image();
img.onload = function () {
$('.select-img').remove();
$('#image').css('display', 'block').attr('src', src).resizable({ aspectRatio: this.width / this.height });
};
img.src = src;
};
fr.readAsDataURL(file);
}
$('.select-img').click(function () {
var fileInput = $(document.createElement("input"));
fileInput.attr('type', 'file');
fileInput.attr('accept', 'image/*');
fileInput.trigger('click');
$(fileInput).on('change', function (ev) {
upload(ev.target.files[0]);
});
return false;
});
</script>
</body>
</html>
Did some intitial testing via FireFox on desktop and Chrome on Android. Both work properly to display the image:
Working Example: https://jsfiddle.net/Twisty/188x0w0u - for mobile testing, use: https://jsfiddle.net/Twisty/188x0w0u/show
JavaScript
$(function() {
function upload(file) {
var fr = new FileReader();
fr.onload = function(event) {
var src = event.target.result;
var img = new Image();
img.onload = function() {
$('.select-img').remove();
$('#image').css('display', 'block').attr('src', src).resizable({
aspectRatio: this.width / this.height
});
};
img.src = src;
};
fr.readAsDataURL(file);
}
$('.select-img').click(function() {
var fileInput = $("<input>", {
type: "file",
accept: "image/*"
});
fileInput.trigger('click');
fileInput.on('change', function(ev) {
upload(ev.target.files[0]);
});
return false;
});
});
Minor switches to code to make better use of jQuery. this worked in both capturing a photo from camera and selecting photo from documents on the mobile device.
Resizing fails, and for me this was expected. Add Touch punch:
https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js
New Test: https://jsfiddle.net/Twisty/188x0w0u/2/
Mobile: https://jsfiddle.net/Twisty/188x0w0u/2/show/
Now the .resizable() works on mobile too.