I can not able to draw the full image using canvas. Here is my code:
<div class="form-group">
<label for="exampleInputEmail1">Coupon Title</label>
<input type="text" name="emails" id="copTitle" class="form-control" placeholder="Add Coupon Title" value="<?php echo $email; ?>" required>
</div>
<div class="couponimg" style="display:none;" id="blankImagediv">
<img class="img-responsive thumbnail" style="margin-bottom:9px; display:none;" src="http://oditek.inimages/coupon-banner-blank.jpg" crossorigin="anonymous" id="requiredImage">
<canvas id="canvas" class="img-responsive thumbnail" style="margin-bottom:9px;"></canvas>
</div>
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = $('#requiredImage').width();
canvas.crossOrigin = "Anonymous";
canvas.height = $('#requiredImage').height();
ctx.drawImage($('#requiredImage').get(0), 0, 0);
ctx.font = ":26pt Calibri";
$(document).on('input','#copTitle',function(){
$('#blankImagediv').css('display','block');
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage($('#requiredImage').get(0), 0, 0);
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(),40,80);
})
Here I am getting the half of the image of original image while drawing. The right hand side of the image is not displaying.
hi try with following code...
var canvas = document.getElementById('canvas'),
img = document.getElementById('requiredImage'),
ctx = canvas.getContext('2d');
img.onload = drawImage;
canvas.width = img.width;
canvas.height = img.height;
ctx.font = ":26pt Calibri";
$(document).on('input', '#copTitle', function() {
$('#blankImagediv').css('display', 'block');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(), 40, 80);
});
function drawImage()
{
ctx.drawImage(img, 0, 0);
}
Related
I'm actually working on a project which overlay two image, with one that the user upload it and the second is by default.
My only problem is when the uploaded image is a rectangle and not a square, the canvas is resizing it. I need that the canvas crop my image, and be a square. Then I can apply the filter.
Here is my code:
$('.file1, .file2').on('change', function() {
var reader = new FileReader(),
imageSelector = $(this).data('image-selector');
if (this.files && this.files[0]) {
reader.onload = function(e) {
imageIsLoaded(e, imageSelector)
};
reader.readAsDataURL(this.files[0]);
}
});
$('.btn-merge').on('click', merge);
function imageIsLoaded(e, imageSelector) {
$(imageSelector).attr('src', e.target.result);
$(imageSelector).removeClass('hidden');
};
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
canvas.width = 300;
canvas.height = 300;
imageObj1.src = $('.image1').attr('src');
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 300, 300);
imageObj2.src = $('.image2').attr('src');
imageObj2.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj2, 0, 0, 300, 300);
var img = canvas.toDataURL('img/png');
$('.merged-image').attr('src', img);
var mergedimage = document.getElementById('mergedimage');
$('.merged-image').removeClass('hidden');
$("#downloadfinal").attr("href", mergedimage.src);
}
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="container-fluid shadow">
<div class="container d-flex flex-column justify-content-center">
<div class="row mb-1 ">
<h2>Votre photo ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file1" type="file" data-image-selector=".image1" />Selectionner un fichier</label>
</div>
<img class="image1 hidden mb-4" alt="abs" width="200px" height="auto" />
<div class="row">
<h2 class="mr-2 ">Filtre par défaut : </h2>
<img alt="abs image3" width="200px" height="auto" src="img/filtre.png" />
</div>
<div class="otherfilter">
<div class="row mt-5 mb-5">
<h2 class="">Mettez un autre filtre ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file2" type="file" data-image-selector=".image2" />Selectionner un fichier</label>
</div>
<img class="hidden image2" alt="ab" width="200px" height="auto" src="img/filtre.png">
</div>
</div>
<br />
<div class="text-center mb-5">
<input class="btn-merge mb-3" type="button" value="Appliquer le filtre" />
<br />
<img class="merged-image hidden mb-3" id="mergedimage" alt="merged image" />
<canvas id="canvas" class="hidden"></canvas>
<br>
<a class="btn-dl" id="downloadfinal" role="button" href="#" download="photo_profil_modifie">
<i class="mr-2 bi bi-download"></i>Télécharger
</a>
</div>
Thanks for read this, hope my english is good, if you don't understand tell me.
To do this you need to scale the input image to fit the canvas either horizontally or vertically while maintaining it's aspect ratio.
That's not hard to do as things are a bit easier since the canvas is squarish. Say we have a canvas of 300 x 300 pixel and we want to draw a non-square image of 400 x 300 onto. First we take the width or height of the canvas - it does not really matter as it's the same - and divide it by the bigger side of the image - 400 in this case.
300 / 400 == 0.75
This is the scale we need to multiply both the width and height of the image before drawing it onto the canvas.
Here's an example:
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width > imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
#canvas {
background: blue;
}
<canvas id="canvas" width="300" height="300"></canvas>
If you prefer to not have unused area on your canvas and stretch the image to the whole canvas and crop the exceess, you simply divide the smaller side of your image by the canvas width/height.
For example:
//ctx.drawImage(imageObj1, 0, 0, 300, 300);let image = new Image();
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width < imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
<canvas id="canvas" width="300" height="300"></canvas>
I'm trying to input text into a html form field (button) which will then be displayed on the same page over an image. Any advice of how I could get the two talking to each other would be really appreciated.
<canvas id="myCanvas" width="900" height="600" style="border:1px solid #404040;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img =new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 900, 600);
function myFunction() {
document.getElementById("line1").innerHTML;
var line1 = document.getElementById("line1").value;
var line2 = document.getElementById("line2").value;
var line3 = document.getElementById("line3").value;
}
//the code below positions the overlaying text on the image
ctx.font = "bold 36px Times";
ctx.fillStyle = "black";
ctx.fillText ("line1",400,325);
ctx.fillText ("line2",400,375);
ctx.fillText ("line3",400,425);
}
//this is the image
img.src= "bus_red.gif"
</script>
//the code below allows the user to input text into boxes
<div>
<form>
<label for="line1">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line1"><br>
<label for="line2">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line2"><br>
<label for="line3">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line3"><br>
//Click the "click-me' button to return the text on the "HTML" button
<button onclick="myFunction()">Click me</button>
</form>
</div>
Try this. For the button, the element being displayed only stays if the user keep on holding the button. Thus I changed it to a radio box where you can style it into a button.
The button has been linked with the canva and the inserted in the different textbox are being displayed respectively.
Edit: I have added a reset code to reset the canva and also styled the two "buttons".
Tested and works
<canvas id="myCanvas" width="900" height="600" style="border:1px solid #404040;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function myFunction() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img =new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 900, 600);
}
//the code below positions the overlaying text on the image
ctx.font = "bold 36px Times";
ctx.fillStyle = "black";
ctx.fillText ( document.getElementById("line1").value ,400,325);
ctx.fillText ( document.getElementById("line2").value ,400,375);
ctx.fillText ( document.getElementById("line3").value ,400,425);
}
img.src= "images/image1.jpg"
function myFunction2() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
//this is the image
</script>
//the code below allows the user to input text into boxes
<div>
<form>
<label for="line1">Enter your text: </label>
<input type="text" autocomplete="off" id="line1" placeholder="line1"><br>
<label for="line2">Enter your text: </label>
<input type="text" autocomplete="off" id="line2" placeholder="line2"><br>
<label for="line3">Enter your text: </label>
<input type="text" autocomplete="off" id="line3" placeholder="line3"><br>
//Click the "click-me' button to return the text on the "HTML" button
<a id="input-button" onclick="myFunction()">Click me</a>
Reset
</form>
</div>
<style>
#input-button {
padding: 2em;
background-color: black;
color: #fff;
}
#input-reset {
padding: 2em;
background-color: black;
color: #fff;
text-decoration: none;
}
</style>
I'm working on a proyect and i need to draw in almost 5 canvas. I've created the first canvas successfully but when i put in the code the second i only can draw on this latest canvas.
I read than the problem can be the context("2d") i tryed to separate saving in a different ctx varaible like, ctx2 or things like this.
This is my code:
HTML
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
</div>
</div>
JS OF THE FIRST CANVAS WORKING OK:
//Canvas Cervical
var canvasCervical = document.getElementById("pizarra-cervical");
var ctx = canvasCervical.getContext("2d");
var painting = document.getElementById("contenedor-pizarra-cervical");
var paintStyle = getComputedStyle(painting);
canvasCervical.width = parseInt(paintStyle.getPropertyValue("width"));
canvasCervical.height = parseInt(paintStyle.getPropertyValue("height"));
var mouse = {x: 0, y: 0};
canvasCervical.addEventListener('mousemove', function(e){
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvasCervical.addEventListener('mousedown', function(e){
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvasCervical.addEventListener('mousemove', onPaint, false);
}, false);
canvasCervical.addEventListener('mouseup', function(){
canvasCervical.removeEventListener('mousemove', onPaint, false)
},false);
var onPaint = function (){
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
If you require the same behaviour to happen on multiple canvasses, then you could define the configuration logic in its own function, providing the canvas element as an argument, like this:
let configureCanvas = canvas => {
let painting = canvas.parentNode;
let paintStyle = getComputedStyle(painting);
let mouse = { x: 0, y: 0 };
let onPaint = () => {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
canvas.width = parseInt(paintStyle.getPropertyValue("width"));
canvas.height = parseInt(paintStyle.getPropertyValue("height"));
let ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false)
}, false);
canvas.nextElementSibling.addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
}
configureCanvas(document.getElementById("pizarra-cervical"));
configureCanvas(document.getElementById("pizarra-postural"));
canvas {
border: 1px solid #CCC;
}
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
<button class="clear">Clear</button>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
<button class="clear">Clear</button>
</div>
</div>
Taking this a step further, I'd suggest defining your own Class to handle the initialisation, configuration and event handlers of your canvas elements, but that's well outside the remit of this question.
That is my problem :
I have written javascript code to create a thumbnail when a user uploads an image. I would now like to add a feature which allows a user to click on an "X" which will then deleted the image.
this is my code :
var imageLoader = document.getElementById('fUpload2');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas2');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
document.getElementById("imageCanvas2").style.height = canvas.height;
document.getElementById("imageCanvas2").style.maxWidth = "200px";
document.getElementById("imageCanvas2").style.maxHeight = "200px";
document.getElementById("imageCanvas2").style.border = "1px solid #000";
}
img.src = event.target.result;
var alte= canvas.height;
}
reader.readAsDataURL(e.target.files[0]);
}
.image-upload-gal > input {
display: none;
}
<div class="well">
<form class="form-horizontal" role="form" method="post" action="/ServiceUpload.php" enctype="multipart/form-data">
<div class="form-group" style="padding:14px;">
<div class="image-upload-gal" >
<label for="fUpload2">
Add foto
</label>
<input type="file" name="fUpload" id="fUpload2" />
<br>
<canvas id="imageCanvas2" ></canvas>
</div>
</div>
<button class="btn btn-primary pull-right" type="submit" value="f_upload" name="up" style="margin-top: -20px;">Submit Photo</button>
</form>
</div>
and that is another code ( i need 2 code is long story :D )
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
.thumb {
height: 180px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
input{
display:none;
}
<div class="image-upload" >
<label for="upload">
Add foto
</label>
<input type="file" id="upload" name="fUpload" />
<input type="hidden" name="up" value="f_upload" />
<output id="list"></output>
</div>
<button class="btn btn-primary pull-right" type="submit" value="newpost" name="NewPost" style="margin-top: -10px;">Submit</button>
</form>
just add an onclick event on a span containing a "x"
<span id="deleteImage">X</span>
Add the on Click handler then clear the canvas as you haven't saved the image anywhere else in that code
document.getElementById("deleteImage").onclick = function(){
canvas.clearRect(0, 0, canvas.width, canvas.height);
}
Edited.
if you want to clear the canvas directly below is how.
canvas = document.getElementById("imageCanvas2");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
Right now i have a form where i can enter some text and it appears in a canvas element,
however when i press backspace the text doesn't go away anymore and when i retype text it appears on top of the old text.
Is there a way to get the canvas element to respond to deleting text also?
<!DOCTYPE html>
<html>
<title>dropIn Print Generator</title>
<body>
<h1>dropIn Print Generator</h1>
<form method="post" action="run.php">
<p>brand name
<input type="text" id="brand" onkeyup="showBrand(this.value)" /></p>
<p>product name
<input type="text" id="product" onkeyup="showProductName(this.value)" /></p>
<p>product details
<input type="text" id="details" onkeyup="showProductDetail(this.value)" /></p>
<p>product sku
<input type="text" id="sku" /></p>
<p>product image
<input type="file" id="image" /></p>
</form>
<canvas id="mainCanvas" width="400" height="600" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
// begin upper shape
context.beginPath();
context.moveTo(0, 0);
context.lineTo(400, 0);
context.lineTo(400, 300);
context.lineTo(380, 30);
context.lineTo(0, 50);
context.lineTo(0, 0);
// complete upper shape
context.closePath();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.fillStyle = 'black';
context.fill();
context.stroke();
// begin bottom shape
context.beginPath();
context.moveTo(400, 600);
context.lineTo(200, 600);
context.lineTo(400, 585);
context.lineTo(400, 600);
// complete bottom shape
context.closePath();
context.lineWidth = 1;
context.strokeStyle = 'black';
context.fillStyle = 'black';
context.fill();
context.stroke();
function showBrand(str){
context.fillStyle = 'black';
context.font = '20px sans-serif';
context.textBaseline = 'bottom';
context.fillText(str, 30, 100);
}
function showProductName(str){
context.fillStyle = 'black';
context.font = '30px sans-serif';
context.textBaseline = 'bottom';
context.fillText(str, 30, 135);
}
function showProductDetail(str){
context.fillStyle = 'black';
context.font = '20px sans-serif';
context.textBaseline = 'bottom';
context.fillText(str, 30, 160);
}
</script>
</body>
</html>
You need to clear the canvas before each time you paint some new text onto it, otherwise anything you've already drawn on the canvas will remain and you'll be drawing on top of it.
function clearCanvas() {
// Redraw the background color over the top of the old text to 'clear' it.
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
}
Add a call to this function to the start of your other 3 drawing functions.