Could not draw multiple text on image using canvas and Javascript - javascript

I need one help. I am unable to draw multiple text on canvas using canvas and Javascript. I am explaining my code below.
<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="form-group">
<label for="coupondiscount">Coupon Discount</label>
<input name="coupondiscount" id="coupondiscount" class="form-control" placeholder="Add Coupon Discount" value="<?php echo $email; ?>" type="text" required>
</div>
<div class="couponimg" style="display:none;" id="blankImagediv">
<img class="img-responsive thumbnail" style="margin-bottom:9px; display:none;" src="images/coupon-banner-blank.jpg" crossorigin="anonymous" id="requiredImage">
<canvas id="canvas" class="img-responsive thumbnail" style="margin-bottom:9px;"></canvas>
</div>
My javascript part is given below.
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 = "26px 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(), 160, 40);
});
$(document).on('input', '#coupondiscount', function() {
console.log('hii');
$('#blankImagediv').css('display', 'block');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(), 180, 90);
});
function drawImage()
{
ctx.drawImage(img, 0, 0);
}
Here i need when user will write text on first input field it will written top of the image and when the user will write text on second input field it will written on the different place of the image but the first text should not replace.Here my problem is each text is replacing with others.Please help me.

I think the reason is you are clearing the canvas each time, and draw the image then insert the text. So it removes the old text and add the new one. Please try the below code if it matches your requirement, may be it helps you.
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 = "26px 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(), 160, 40);
});
$(document).on('input', '#coupondiscount', function() {
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(), 180, 90);
});
function drawImage()
{
ctx.drawImage(img, 0, 0);
}

Related

How to turn HTML form input into Javascript variable?

I'm making a new game, I want the amount of circles in the game to be inputed by the player, but am having difficulty setting up the variable from HTML into javascript.
I have determined that the problem only relies on the 'i' variable not being set correctly, since replacing 'document.getElementsByName('circles').value;' with any number works fine.
<div>
<form>
<input type="number" Name="circles" id = "circles" min="2" max="50"
value="2">
<input type="submit">
</form>
</div>
<div id="container">
<canvas id="myCanvas" width="800" height="800">
</canvas>
</div>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = document.getElementsByName('circles').value;
for (i; i > 0; i= i-1) {
ctx.beginPath();
ctx.arc(Math.random()*c.width+1, Math.random()*c.height+1, 25, 0, 2 *
Math.PI);
ctx.stroke();
}
</script>
I expect the number of appearing circles to be the same as the given value, but instead nothing happens.
Get value by id not using names and make input type as button not submit.
function a(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = document.getElementById('circles').value;
console.log(i)
for (i; i > 0; i= i-1) {
ctx.beginPath();
ctx.arc(Math.random()*c.width+1, Math.random()*c.height+1, 25, 0, 2 *
Math.PI);
ctx.stroke();
}}
<div>
<form>
<input type="number" Name="circles" id = "circles" min="2" max="50"/>
<input type="button" onclick='a()' value="Click"/>
</form>
</div>
<div id="container">
<canvas id="myCanvas" width="800" height="800">
</canvas>
</div>

How to save canvas into database

Im doing a project which is web based abc tracing program.In my program,i should have a save button which will convert the drawing in canvas into image any automatically save the image in database.I dont know how to do this.I can convert the drawing into image but i dont know how to save into database.
This is my coding
html
<html>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display+SC:700" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Playball" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="cssdrawing.css">
<script src="a.js"></script>
<body>
<div style="background:A5F0FA;padding:10px;padding-bottom:20px">
<h1 style="font-family: 'Playfair Display SC', serif;text-align:center;margin-bottom:10px">Lets Trace!</h1>
<hr style="margin-bottom:15px;padding-top:0px;" width="500px" />
<center>
<div align="center" id="MainDiv" style="background:#FAA5EE;box-shadow:5px 5px 5px silver;padding:10px;max-width:90%;">
<canvas id="painter" height="300px" width="500" style="background: url('./images/vtr.jpg')"></canvas>
<br />
<div class="holder">
<span>Colors:</span>
<input type="button" style="background-color:FF0000;padding:10px 24px" onclick="Color('red')"></button>
<input type="button" style="background-color:0000FF;padding:10px 24px" onclick="Color('blue')"></button>
<input type="button" style="background-color:DE5616;padding:10px 24px" onclick="Color('brown')"></button>
<input type="button" style="background-color:FFFF00;padding:10px 24px" onclick="Color('yellow')"></button>
<input type="button" style="background-color:008000;padding:10px 24px" onclick="Color('green')"></button>
<input type="button" style="background-color:DE168F;padding:10px 24px" onclick="Color('pink')"></button>
<input id="color" type="color" onclick="Color(this.value)" onchange="Color(this.value)"></input>
<br /></div>
<div class="holder">
<span>Thickness:</span>
<input value="30" id="number" min="30" max="100" type="number"></input><br /></div>
<div class="holder">
<span>Other:</span>
<button onclick="Color('white')">Eraser</button>
<button onclick="ClearCanvas()">Clear Canvas</button>
<a id="download" download="img.jpg"><button type="button" onClick="download()">Save</button></a>
</div>
</div>
</center>
</div>
</body>
</html>
Javascript
function Color(a) {
var offset = function(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
var canvas = document.getElementById("painter");
var context = canvas.getContext("2d");
var draw = false;
var pos = offset(canvas);
canvas.onmousemove = function(e) {
if (draw == false) { return; }
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
console.log(x,y);
context.lineTo(x, y);
context.stroke();
}
canvas.onmousedown = function(e) {
draw = true;
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
context.fillStyle = "red";
context.beginPath();
context.moveTo(x, y);
context.lineWidth= document.getElementById("number").value;
context.strokeStyle=a;
}
canvas.onmouseup = function(e) {
draw = false;
}
}
function ClearCanvas() {
var c=document.getElementById("painter");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,880,300);
}
function Preview() {
var canvas = document.getElementById("painter");
var dataUrl = canvas.toDataURL();
window.open(dataUrl, "", "width=880, height=300");
}
function download(){
var download = document.getElementById("download");
var image = document.getElementById("painter").toDataURL("image/jpg")
.replace("image/jpg", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.jpg");
$.ajax({
method: 'POST',
url: 'photo_upload.php',
data: {
photo: photo
}
});
}
Send that dataUrl back to your server with an AJAX post
$.ajax({
type: "POST",
url: "photo_upload.php",
data: {photo : dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
On the PHP side, save the incoming dataURL to a database:
<?php
$sql="insert into table_name(photo) values(:photo)";
// INSERT with named parameters
$conn = new PDO('mysql:host=localhost;dbname=myDB', "root", "myPassword");
$stmt = $conn->prepare($sql);
$stmt->bindValue(":photo",$_POST["photo"]);
$stmt->execute();
$affected_rows = $stmt->rowCount();
echo $affected_rows;
?>

Issue when trying to change font size and color in canvas

I'm trying to change my font size and color in my canvas on a photo. So you have to upload a photo before you're able to add text to the image. After you add the photo and add text, then you're able to change the color and font, but when trying to do so you have to re-submit or the changes are not applied. Any ideas on what is happening? Do I have to re-draw it when they change colors or font sizes? Thanks In advance.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="theText" type="text">
<button id="submit">Draw text on canvas</button>
<br>
<canvas id="canvas" width="1000" height="500" class="playable-canvas"></canvas>
<div id="image_div">
<h1> Choose an Image to Upload </h1>
<input type='file' name='img' id='uploadimage' />
</div>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.filter = 'blur(0px)';
</textarea>
<!-- Change Font Size -->
<div class="radio">
<input type="radio" name="radio" id="size16" onclick="size16()" checked="">
<label for="size16"> Font Size 16 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size20" onclick="size20()" >
<label for="size20"> Font Size 20 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size25" onclick="size25()" >
<label for="size25"> Font Size 25 </label>
</div>
<div class="radio">
<input type="radio" name="radio"id="size30" onclick="size30()" >
<label for="size30"> Font Size 30</label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size35" onclick="size35()" >
<label for="size35"> Font Size 35 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size40" onclick="size40()" >
<label for="size40"> Font Size 40 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size45" onclick="siz45()" >
<label for="size45"> Font Size 45 </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="size50" onclick="size50()" >
<label for="size50"> Font Size 50 </label>
</div>
<Br>
<!-- Change Color on Text -->
<div class="col-lg-2 col-md-2 col-xs-12">
<div class="radio">
<input type="radio" name="radio" id="black" onclick="BlackText()" checked="">
<label for="radio1"> Black </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="white" onclick="WhiteText()" >
<label for="radio1"> White </label>
</div>
<div class="radio">
<input type="radio" name="radio" id="yellow" onclick="YellowText()" >
<label for="radio1"> Yellow </label>
</div>
<div class="radio radio-primary">
<input type="radio" name="radio" id="blue" onclick="BlueText()" >
<label for="radio3"> Blue </label>
</div>
<div class="radio radio-success">
<input type="radio" name="radio" id="green" onclick="GreenText()" >
<label for="radio4"> Green </label>
</div>
<div class="radio radio-danger">
<input type="radio" name="radio"id="red" onclick="RedText()" >
<label for="radio6"> Red </label>
</div>
<div class="radio radio-warning">
<input type="radio" name="radio" id="orange" onclick="OrangeText()" >
<label for="radio7"> Orange </label>
</div>
<div class="radio radio-purple">
<input type="radio" name="radio"id="purple" onclick="PurpleText()" >
<label for="radio8"> Purple </label>
</div>
</div>
Javscript:
//===========================================================================================================================
// Javascript that loads Image into canvas
//===========================================================================================================================
var drawnImage;
function drawImage(ev) {
console.log(ev);
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
drawnImage = img;
ctx.drawImage(img, 0, 0);
url.revokeObjectURL(src);
}
}
document.getElementById("uploadimage").addEventListener("change", drawImage, false);
//===========================================================================================================================
// Javascript for input in textbox
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
drawImage();
}
reset.addEventListener('click', function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener('click', function() {
textarea.focus();
})
textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
//===========================================================================================================================
// Javascript for Moving Text around.
//===========================================================================================================================
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var startX;
var startY;
var texts = [];
var selectedText = -1;
function draw() {
ctx.rect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
// ctx.fillStyle = "blue";
ctx.fillText(text.text, text.x, text.y);
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(drawnImage, 0, 0);
draw();
}
function textHittest(x, y, textIndex) {
var text = texts[textIndex];
return (x >= text.x && x <= text.x + text.width && y >= text.y - text.height && y <= text.y);
}
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
for (var i = 0; i < texts.length; i++) {
if (textHittest(startX, startY, i)) {
selectedText = i;
}
}
}
function handleMouseUp(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseOut(e) {
e.preventDefault();
selectedText = -1;
}
function handleMouseMove(e) {
if (selectedText < 0) {
return;
}
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
var dx = mouseX - startX;
var dy = mouseY - startY;
startX = mouseX;
startY = mouseY;
var text = texts[selectedText];
text.x += dx;
text.y += dy;
redraw();
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
$("#submit").click(function() {
var y = texts.length * 20 + 20;
var text = {
text: $("#theText").val(),
x: 20,
y: y
};
// ctx.font = "16px verdana";
text.width = ctx.measureText(text.text).width;
text.height = 16;
texts.push(text);
draw();
});
//===========================================================================================================================
// Javascript for Text Size :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function size16 () {
ctx.font = "16px verdana";
}
function size20 () {
ctx.font = "20px verdana";
}
function size25 () {
ctx.font = "25px verdana";
}
function size30 () {
ctx.font = "30px verdana";
}
function size35 () {
ctx.font = "35px verdana";
}
function size40 () {
ctx.font = "40px verdana";
}
function size45 () {
ctx.font = "45px verdana";
}
function size50 () {
ctx.font = "50px verdana";
}
//===========================================================================================================================
// Javascript for Drop down for Text Color :)
//===========================================================================================================================
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function PurpleText () {
ctx.fillStyle= 'purple';
}
function BlackText () {
ctx.fillStyle= 'black';
}
function YellowText () {
ctx.fillStyle= 'yellow';
}
function OrangeText () {
ctx.fillStyle = "orange";
}
function BlueText () {
ctx.fillStyle= 'blue';
}
function WhiteText () {
ctx.fillStyle = "white";
}
function GreenText () {
ctx.fillStyle= 'green';
}
function RedText () {
ctx.fillStyle = "red";
}
You have either to draw again the canvans or draw (refresh) it continuosly every xxx milliseconds.

how to use buttons to call functions that draw in canvas

For this project, we're working with canvas. I need to create some buttons, and when you click on the buttons, the corresponding function should be called. These functions will then draw something in the canvas. However, my code isn't working. The buttons and the canvas themselves appear, but nothing draws when you click on the buttons. Are there any errors?
<script>
function drawCircle(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
}
function drawLine(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
}
function drawRectangle(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
function drawImage(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
}
function drawText(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<input type="button" onclick="drawCircle();" value="Draw Circle">
<input type="button" onclick="drawLine();" value="Draw Line">
<input type="button" onclick="drawRectangle();" value="Draw Rectangle">
<input type="button" onclick="drawImage();" value="Draw Line">
<input type="button" onclick="drawText();" value="Text">
<input type="button" onclick="drawGradient();" value="Gradient">
<input type="button" onclick="scale();" value="Scale">
</body>
</html>
I tried your code in CodePen and the buttons for which you've implemented the function work just fine. Does your console show any errors?

Drawing a line in Canvas with user input

I'm trying to draw a line in Canvas when a user gives the X and Y coordinates. This is what I have so far. I can get the canvas and the input boxes it won't draw though. I'm a newbie so any advice is appreciated.
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var y1 = document.getElementById("y1").value;
var y2 = document.getElementById("y2").value;
function draw(){
context.beginPath();
context.moveTo(x1.value,y1.value);
context.lineTo(x2.value,y2.value);
context.stroke();
}
</script>
<br><br>
<h1>Draw a Line</h1>
X-coordinate 1 <input type="text" id="start_x"><br><br>
Y-coordinate 1<input type="text" id="start_y"><br><br>
X-coordinate 2<input type="text" id="end_x"><br><br>
Y-coordinate 2<input type="text" id="end_y"><br><br>
<input type="button" value="draw" onclick="draw()">
It's giving you undefined because you set your input id as start_x, start_y,end_x,end_y and in your js you are getting the value as x1,x2,y1,y2.
html
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;">
</canvas>
<h1>Draw a Line</h1>
<form>
X-coordinate 1 <input type="text" id="start_x"><br><br>
Y-coordinate 1<input type="text" id="start_y"><br><br>
X-coordinate 2<input type="text" id="end_x"><br><br>
Y-coordinate 2<input type="text" id="end_y"><br><br>
<input type="button" value="draw" onclick="draw()">
</form>
js
function draw(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x1 = document.getElementById("start_x").value;
var x2 = document.getElementById("start_y").value;
var y1 = document.getElementById("end_x").value;
var y2 = document.getElementById("end_y").value;
context.beginPath();
context.moveTo(x1,x2);
context.lineTo(y1,y2);
context.stroke();
}
Rewrite your code this way;
<canvas width="300" height="300" id="myCanvas"></canvas><br /><br />
X-coordinate 1<input type="text" id="x1"><br><br>
Y-coordinate 1<input type="text" id="y1"><br><br>
X-coordinate 2<input type="text" id="x2"><br><br>
Y-coordinate 2<input type="text" id="y2"><br><br>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function draw(){
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var y1 = document.getElementById("y1").value;
var y2 = document.getElementById("y2").value;
context.beginPath();
context.strokeStyle="#FF0000";
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.stroke();
}
</script>
<br><br>
<h1>Draw a Line</h1>
<input type="button" value="draw" onclick="draw()">
your draw function is called onclick but the function uses the input value which was set as 'undefined' because when window loaded the value of the input was not defined, to resolve this you should include your code of getting those values in the draw function.

Categories