disabling button when input field is empty not working in javascript - javascript

I am trying to disable my download button when the field is empty, when the user types the name only it should show. because without entering text also the user is able to download image. I have done the following code:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<div class="container">
<div style="margin-top: 5%; " class="row">
<?php
require('db_config.php');
$id=$_GET['editid'];
$sql = "SELECT * FROM image_gallery where id='$id'";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div style="margin-left: 5%;" class="col-md-5"><canvas id="imageCanvas"></canvas></div>
<div style="margin-left: 2%; margin-top: 10%;" class="col-md-5 col-sm-8">
<div class="modal-content">
<div class="modal-header">
<h4 class="something"><span class="sims">Card Name: &nbsp</span>
<?php echo $image['title']; ?>
</h4>
<div class="modal-body">
<form method="post" action="" id="form_name">
<div class="row">
<div class="col-md-12">
<input class="lolan" type="text" id="name" placeholder="Full Name" required />
<!-- <label for="name" class="form__label">Full Name</label> -->
</div>
<div id="chumma" class="col-md-12">
<button id="download" type="submit" onclick="download_image()" name="button" value="Download" class="btn btn-primary">Download</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var text_title = "Heading";
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
// img.crossOrigin = "anonymous";
window.addEventListener('load', DrawPlaceholder)
function DrawPlaceholder() {
img.onload = function() {
DrawOverlay(img);
DrawText(text_title);
DynamicText(img)
};
img.src = 'uploads/<?php echo $image['
image '];?>';
}
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 500;
canvas.height = 500;
function DrawOverlay(img) {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(230, 14, 14, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function DrawText(text) {
ctx.fillStyle = "black";
ctx.textBaseline = 'middle';
ctx.font = "50px 'Montserrat'";
ctx.fillText(text, 150, 250);
}
function DynamicText(img) {
document.getElementById('name').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
text_title = this.value;
DrawText(text_title);
});
}
function download_image() {
var canvas = document.getElementById("imageCanvas");
image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var link = document.createElement('a');
link.download = "my-image.png";
link.href = image;
link.click();
}
</script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
validate();
$('#name').change(validate);
});
function validate() {
if ($('#name').val().length > 0 && {
$("#download").prop("disabled", false);
}
else {
$("#download").prop("disabled", true);
}
}
</script>
<?php } ?>
but this is not making the button from disabling when the input is empty. can anyone please tell me what is wrong in my code. thanks in advance

Your code has some syntax errors and you should use keyup event:
$(document).ready(function() {
validate();
$('#name').keyup(validate);
});
function validate() {
if ($('#name').val().length > 0) {
$("#download").prop("disabled", false);
}
else {
$("#download").prop("disabled", true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name">
<button id="download">Download</button>

I've noticed 2 things in your JavaScript code:
$('#name').change(validate); is triggered only when you exit (blur) the field.
Instead, you can use:
$('#name').keyup(validate);
There's a syntax error at:
if ($('#name').val().length > 0 && {
You should close the parenthesis like:
if ($('#name').val().length > 0 ) {
Hope this helps!

Related

HTML javascript, dragging method in canvas

I made a square grid using HTML canvas and I am implementing a drag mechanism, such that the user can draw only rectangles by dragging over the grid.
In the below solution, the user can draw non-rectangle shapes, depending on how the user drags.
An additional question : The grid can be of any size and the drag operation is laggy for large rectangles. Any performance improvement suggestions for that ?
Here are my code of html and javascript
function getSquare(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: 1 + (evt.clientX - rect.left) - (evt.clientX - rect.left)%10,
y: 1 + (evt.clientY - rect.top) - (evt.clientY - rect.top)%10
};
}
function emptySquare(context) {
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#ffffff"
context.fill();
context.strokeStyle = "#ddd";
context.stroke();
}
function range(start, end) {
var ans = [];
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i);
}
} else {
emptySquare(context);
for (let i = start; i >= end; i -= 10) {
ans.push(i);
}}
return ans;
}
function drawBoard(context) {
for (var x = 0.5; x < 20001; x += 10) {
context.moveTo(x, 0);
context.lineTo(x,20000);
}
for (var y = 0.5; y < 20001; y += 10) {
context.moveTo(0, y);
context.lineTo(20000, y);
}
context.strokeStyle = "#ddd";
context.stroke();
}
function fillSquare(context, x, y){
context.fillStyle = "#70B7B5";
context.fillRect(x,y,9,9);
}
var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');
var A;
drawBoard(context);
var isDrag= false;
// drawBoard(context);
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt);
isDrag=true;
fillSquare(context, mousePos.x, mousePos.y);
previousPos = mousePos;
}, false);
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt);
var x_dist = range(previousPos.x, mousePos.x);
var y_dist = range(previousPos.y, mousePos.y);
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y]);
}
}
}
}, false);
canvas.addEventListener('mouseup', function(evt) {
if (isDrag){
isDrag = false;
}
}, false);
var canvas = document.getElementById('myBoard');
var context = canvas.getContext('2d');
// drawBoard(context);
var isDrag=false;
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt);
isDrag=true;
fillSquare(context, mousePos.x, mousePos.y);
previousPos = mousePos;
}, false);
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt);
var x_dist = range(previousPos.x, mousePos.x);
var y_dist = range(previousPos.y, mousePos.y);
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y]);
}
}
}
}, false);
canvas.addEventListener('mouseup', function(evt) {
if (isDrag){
isDrag = false;
}
}, false);
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="./assets/css/style.css">
<meta charset="utf-8">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">t</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" aria-current="page" href="index.html">Home</a>
<a class="nav-link" href="#">About Us</a>
<a class="nav-link" href="Myblock.html">Mk</a>
</div>
<div class="navbar-nav ms-auto mb-2 mb-lg-0">
<a class="nav-link" href="login.html">Login</a>
</div>
</div>
</div>
</nav>
<div>
<div class="modal fade bd-example-modal-lg" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">간판 구입</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="POST" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="preview-zone hidden">
<div class="box box-solid">
<div class="box-header with-border">
<div><b>미리보기</b></div>
<!-- <div class="box-tools pull-right">
<button type="button" class="btn btn-danger btn-xs remove-preview">
<i class="fa fa-times"></i> 초기화
</button>
</div> -->
</div>
<div class="box-body"></div>
</div>
</div>
<div class="dropzone-wrapper">
<div class="dropzone-desc">
<i class="glyphicon glyphicon-download-alt"></i>
<p>광고 이미지 선택 or 드래그해 옮겨 오세요.</p>
</div>
<input type="file" name="img_logo" class="dropzone">
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">닉네임/이름</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="닉네임/이름">
<label for="exampleInputEmail1">연락처</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="핸드폰 번호">
<label for="exampleInputEmail1">구매희망 면적</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="ex) 10 x 10 OR 100x100 ">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
<button type="submit" class="btn btn-dark">적용하기</button>
</div>
</div>
</div>
</div>
<div>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>
</hr>
<footer>
<p>© 2021 Nune Project</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="./assets/js/mainBoard.js"></script>
<script type="text/javascript" src="./assets/js/drag_field.js"></script>
</body>
The issue is being seen because range function is not clearing the squares when end > start. Clearing the squares in both the cases resolves the issue.
Here's the snippet that fixes the issue.
function range(start, end) {
var ans = [];
emptySquare(context);
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i);
}
} else {
for (let i = start; i >= end; i -= 10) {
ans.push(i);
}
}
return ans;
}
The Lag Issue
The callback function attached to mousemove clears and draws squares on every invocation - a time consuming operation. Given that JavaScript is single threaded and this function is called at a very high rate, it might be the cause of the lag.
Debouncing the mousemove callback can help reducing the lag.
Another approach to solve the lag issue is to make two canvases: one for the background grid lines and the other one for drawing the green rectangles.
<div>
<canvas id="bg" width="1440" height="1200"></canvas>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>
Set the #bg canvas so that #myBoard is in front of it:
#bg {
position: absolute;
z-index: -1;
}
Then draw the grid lines on the #bg canvas:
const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)
Finally, move the emptySquare(context) function into the mousemove event callback and edit it as follows:
function emptySquare(context) {
context.clearRect(0, 0, canvas.width, canvas.height)
}
So it will only clear the #myBoard canvas while #bg stays the same without needing to redraw it each time.
Example:
const bg = document.getElementById('bg')
const bgContext = bg.getContext('2d')
drawBoard(bgContext)
function getSquare(canvas, evt) {
var rect = canvas.getBoundingClientRect()
return {
x: 1 + (evt.clientX - rect.left) - ((evt.clientX - rect.left) % 10),
y: 1 + (evt.clientY - rect.top) - ((evt.clientY - rect.top) % 10),
}
}
function emptySquare(context) {
context.clearRect(0, 0, canvas.width, canvas.height)
}
function range(start, end) {
var ans = []
if (end > start) {
for (let i = start; i <= end; i += 10) {
ans.push(i)
}
} else {
for (let i = start; i >= end; i -= 10) {
ans.push(i)
}
}
return ans
}
function drawBoard(context) {
for (var x = 0.5; x < 20001; x += 10) {
context.moveTo(x, 0)
context.lineTo(x, 20000)
}
for (var y = 0.5; y < 20001; y += 10) {
context.moveTo(0, y)
context.lineTo(20000, y)
}
context.strokeStyle = '#ddd'
context.stroke()
}
function fillSquare(context, x, y) {
context.fillStyle = '#70B7B5'
context.fillRect(x, y, 9, 9)
}
var canvas = document.getElementById('myBoard')
var context = canvas.getContext('2d')
var isDrag = false
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getSquare(canvas, evt)
isDrag = true
fillSquare(context, mousePos.x, mousePos.y)
previousPos = mousePos
}, false)
canvas.addEventListener('mousemove', function(evt) {
if (isDrag) {
var mousePos = getSquare(canvas, evt)
var x_dist = range(previousPos.x, mousePos.x)
var y_dist = range(previousPos.y, mousePos.y)
emptySquare(context)
for (x in x_dist) {
for (y in y_dist) {
fillSquare(context, x_dist[x], y_dist[y])
}
}
}
}, false)
canvas.addEventListener('mouseup', function(evt) {
if (isDrag) {
isDrag = false
}
}, false)
#bg {
position: absolute;
z-index: -1;
}
<div>
<canvas id="bg" width="1440" height="1200"></canvas>
<canvas id="myBoard" width="1440" height="1200"></canvas>
</div>

How can I fill "ğ" to the text without any corruption?

I try to make a email signature generator using canvas. Because Turkish names include letters like "ğ" that does not exist in utf-8, when I fill the text to the canvas, it is corrupted, but when I click button twice, corruption is does not exist anymore. How can I fix this?
codes are here:
$("#formButton").click(function() {
var name = $("#formName").val();
var title = $("#formTitle").val();
Promise.all([
document.fonts.load("700 32px Roboto"),
document.fonts.load("300 20px Roboto"),
]).then(() => {
var canvas = document.getElementById("canvas-top");
var ctx = canvas.getContext("2d");
ctx.font = "700 32px Roboto";
ctx.fillStyle = "#1F5890";
ctx.fillText(name, 15, 80);
ctx.font = "300 20px Roboto";
ctx.fillStyle = "#1F5890";
ctx.fillText(title, 15, 105);
});
console.log(name, title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;500;700&display=swap" />
<form>
<input type="text" id="formName" value="Gündoğdu" />
<input type="text" id="formTitle" value="Gündoğdu" />
<input type="button" id="formButton" value="Click" />
</form>
<canvas id="canvas-top"></canvas>
Based on you comment you load the font with this URL https://fonts.googleapis.com/css2?family=Roboto:wght#300;500;700
The important part here is that google fonts is delivering the font splitter into multiple files for different character sets, which are loaded on demand.
Drawing the text triggers the loading of the required file, but the drawing happens before that file was loaded.
That's why your letter does not appear correctly for the first draw but will be correct when you trigger the draw a second time.
One thing you could do is to utilize the text parameter of the fonts.load function, and pass the text you want to draw with that font:
$("#formButton").click(function() {
var name = $("#formName").val();
var title = $("#formTitle").val();
Promise.all([
document.fonts.load("700 32px Roboto", name),
document.fonts.load("300 20px Roboto", title),
]).then(() => {
var canvas = document.getElementById("canvas-top");
var ctx = canvas.getContext("2d");
ctx.font = "700 32px Roboto";
ctx.fillStyle = "#1F5890";
ctx.fillText(name, 15, 80);
ctx.font = "300 20px Roboto";
ctx.fillStyle = "#1F5890";
ctx.fillText(title, 15, 105);
});
console.log(name, title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;500;700&display=swap" />
<form>
<input type="text" id="formName" value="Gündoğdu" />
<input type="text" id="formTitle" value="Gündoğdu" />
<input type="button" id="formButton" value="Click" />
</form>
<canvas id="canvas-top"></canvas>

download button not downloading image in javascript

i have an html canvas in which the image is being displayed from database, user can add dynamic text to image and download that image with the text entered. Following is my code:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<div class="container">
<div style="margin-top: 5%;" class="row">
<?php
require('db_config.php');
$id=$_GET['editid'];
$sql = "SELECT * FROM image_gallery where id='$id'";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div class="col-md-5"><canvas id="imageCanvas"></canvas></div>
<div class="col-md-1"></div>
<div style="margin-left: 2%;" class="col-md-5">
<div class="modal-content">
<div class="modal-header">
<h4 class="something">
<?php echo $image['title']; ?>
</h4>
<div class="modal-body">
<form method="post" action="" id="form_name">
<div class="row">
<div class="col-md-12">
<input class="lolan" type="text" id="name" placeholder="Full Name" required />
<!-- <label for="name" class="form__label">Full Name</label> -->
</div>
<div id="chumma" class="col-md-12">
<button id="download" type="submit" onclick="download_image()" name="button" value="Download" class="btn btn-primary">Download</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var text_title = "Heading";
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
// img.crossOrigin = "anonymous";
window.addEventListener('load', DrawPlaceholder)
function DrawPlaceholder() {
img.onload = function() {
DrawOverlay(img);
DrawText(text_title);
DynamicText(img)
};
img.src = 'uploads/<?php echo $image['
image '] ?>';
}
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 500;
canvas.height = 500;
function DrawOverlay(img) {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(230, 14, 14, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function DrawText(text) {
ctx.fillStyle = "black";
ctx.textBaseline = 'middle';
ctx.font = "50px 'Montserrat'";
ctx.fillText(text, 50, 50);
}
function DynamicText(img) {
document.getElementById('name').addEventListener('keyup', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
DrawOverlay(img);
text_title = this.value;
DrawText(text_title);
});
}
function download_image() {
var canvas = document.getElementById("mcanvas");
image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var link = document.createElement('a');
link.download = "my-image.png";
link.href = image;
link.click();
}
</script>
<?php } ?>
now when i click the download button, its not downloading the image. can anyone please tell me what is wrong in here, thanks in advance
When you place a button inside a form by default the click event on the button will make the form to submit. You have to prevent it from happening.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
document.getElementById('download').addEventListener('click', function(e){
e.preventDefault();
download_image()
});
use this instead of using onclick=download_image() user this methods.
another solution How to prevent default event handling in an onclick method?

CROPPER JS Get cropper canvas not working with larger files

I am using https://github.com/fengyuanchen/cropperjs/ but it has a problem in getCroppedCanvas function ,
It's working just fine with small images but not showing when it comes to larger images
result.appendChild(cropper.getCroppedCanvas());
I am using this live example https://fengyuanchen.github.io/cropperjs/examples/upload-cropped-image-to-server.html; source code:
<!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, shrink-to-fit=no">
<title>Cropper.js</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/cropper.css">
<style>
.label {
cursor: pointer;
}
.progress {
display: none;
margin-bottom: 1rem;
}
.alert {
display: none;
}
.img-container img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Upload cropped image to server</h1>
<label class="label" data-toggle="tooltip" title="Change your avatar">
<img class="rounded" id="avatar" src="https://avatars0.githubusercontent.com/u/3456749?s=160" alt="avatar">
<input type="file" class="sr-only" id="input" name="image" accept="image/*">
</label>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
<div class="alert" role="alert"></div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Crop the image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar');
var image = document.getElementById('image');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
$alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob, 'avatar.jpg');
$.ajax('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function () {
$alert.show().addClass('alert-success').text('Upload success');
},
error: function () {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function () {
$progress.hide();
},
});
});
}
});
});
</script>
</body>
</html>
the cropper script is in: https://fengyuanchen.github.io/cropperjs/js/cropper.js
Using croppiejs helped me solve this issue. To utilize Croppie with a preview, you just set the value of an html image element to croppie's base64 result:
First create croppie instance:
var cropperlg = new Croppie(document.getElementById('croppie-lg'), {
viewport: {
width: 400
height: 800
},
boundary: {
height: 500
width: 1000
}
});
This bit of code binds croppie to an image and executes the crop on click.
EDIT: I simplified the code for a more basic example.
cropperlg.bind({
url: '/images/someimg.jpg'
});
$('#crop-btn').on('click', (e) => {
cropperlg.result({
type: 'canvas',
size: { width: 1000, height: 400 }
}).then(function(result) {
$('#cropped-img').attr('src', result);
})
});
You should be able to figure it out from here.
this worked for me
var cropper = $('#cropper-image').cropper('getCroppedCanvas', {
// Limit max sizes
maxWidth: 4096,
maxHeight: 4096,
});
After setting this, it worked well on both mobile and desktop.

Display images randomly on canvas

I need help to code this using Javascript and HTML5. Please advise!
<HTML>
<HEAD>
<SCRIPT language="javascript">
function Add() {
if (document.getElementById('amount').value < 100){
document.getElementById('amount').value++;
newIMG = document.createElement("IMG");
newIMG.src = 'jef-frog.gif';
newIMG.width = 50;
newIMG.height = 50;
document.getElementById("imagedest").appendChild(newIMG);
}
}
function Remove() {
if(document.getElementById('amount').value > 0)
document.getElementById('amount').value--;
imagedest.removeChild(imagedest.lastChild);
}
function numeralsOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</SCRIPT>
</HEAD>
<BODY>
<H2>TESTING</H2>
PREY
<BR/>
<img src="jef-frog.gif" alt="frogsonice.com" width="100" height="100"/>
<BR/>
<FORM>
<INPUT type="button" value="+" onClick="Add()">
<input type="text" id="amount" value=0 maxlength="3" size="1" onkeypress="return numeralsOnly(event)">
<INPUT type="button" value="-" onClick="Remove()">
<div id='imagedest'>
</div>
</FORM>
</BODY>
</HTML>
I have tested the code, it will display in a <div> tag but I want to make it to appear in a canvas created above. I have no idea how to capture the thing in canvas. Can anyone help?
You need to use the canvas api to draw something on it
get the canvas (var canvas = document.getElementById("canvas"); )
get the 2D context(var ctx = canvas.getContext("2d");)
draw the image (https://developer.mozilla.org/en/Canvas_tutorial/Using_images)
Example with a shape
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>

Categories