I'm having a hard time to understand how to work with canvas
elements in JavaScript.
I'm implementing a resize feature where user can resize image inside the lightbox
. The lightbox
will launch after preview image is been clicked. Inside the lightbox
element, in addition of the image itself, there are two input fields for width and height.
The objective is to generate a copy of the original image in base64
format and send it to the server along with given width and height as query parameters and let the server side do the resize operation (I'm using PHP for my back end) or even better, let JavaScript do the resize operation in the front end and return new, resized image ready to be sent to the server via ajax
.
The problem is that I don't exactly know how to deal with dynamically created canvas
elements and how can I use it to resize my image in the front end.
Underneath is what I've tried so far with poor results:
index.html (basic HTML elements and the lightbox effect are omitted)
<!-- input fields for width and height -->
<div class="container">
<div class="form-inline">
<div class="form-group">
<input type="number" class="form-control" id="width" placeholder="px">
</div>
<div class="form-group">
<input type="number" class="form-control" id="height" placeholder="px">
</div>
<button id="resize" type="button" class="btn btn-primary">Resize</button>
</div>
</div>
<!-- preview image -->
<div class="container">
<img src="img/img1.jpg" alt="" class="img-responsive" id="preview">
</div>
<script type="text/javascript">
button = document.getElementById("resize");
button.addEventListener("click", function() {
// get image
const image = document.getElementById('preview');
// create a canvas element
var canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
canvas.width = image.width; // destination canvas size
canvas.height = canvas.width * image.height / image.width;
ctx.drawImage(image, 0, 0, image.width, image.height);
var canvasData = canvas.toDataURL("image/jpeg");
// ajax call
var xhr = new XMLHttpRequest();
var params = "photo=" + encodeURIComponent(canvasData) + "&name=" + encodeURIComponent(name) + "&width="+ encodeURIComponent(width) + "&height=" + encodeURIComponent(height);
// send request
xhr.open("POST", "admin.php?" + params);
xhr.send();
});
</script>
admin.php (nothing fancy here, just decode the image and write it to a folder)
<?php
if(isset($_POST['photoUpload']) && isset($_POST['name'])) {
// decode base64 formatted image
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $_POST['photoUpload']));
if(isset($_POST['width'] && $_POST['height'])) {
// resize image here using imagemagick
}
// write file to "img" directory
file_put_contents(dataPath.'img/'.$_POST['name'], $data);
// done
exit('OK|'.dataPath.'img/'.$_POST['name']);
}
Any tips, tricks and advices are much appreciated !