Converting canvas to image does not include images on the canvas - javascript

I want to convert a canvas to a png image and put it on a page. My problem is that if I have an image on my canvas, it does not get converted. This is my HTML:
<html>
<head>
<meta charset='UTF-8'>
<link rel="stylesheet" type="text/css" href="./assets/css/general.css">
<script type="text/javascript" src="./codetests.js"></script>
</head>
<body>
<div class="wrapper" id="wrap1">
<img id="persphoto" src="./images/nouserimage.png" style="display:none;">
<input type="hidden" id="persname" value="Test Testinen">
<input type="hidden" id="adress" value="Testgatan 1">
<input type="hidden" id="postaddr" value="12345 Teststad">
<input type="hidden" id="homephone" value="0123456789">
<input type="hidden" id="cellphone" value="0712345678">
<canvas src="" id="canvasresult" width="296px" height="420px" />
<br>
</div>
<script type="text/javascript"> drawCanvas(); </script>
<script type="text/javascript"> convertCanvasToImage(canvasresult); </script>
</body>
</html>
My JavaScript is the following:
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
//return image;
document.getElementById("wrap1").appendChild(image);
}
function drawCanvas() {
var c = document.getElementById("canvasresult");
h=parseInt(document.getElementById("canvasresult").getAttribute("height"));
w=parseInt(document.getElementById("canvasresult").getAttribute("width"));
//get context
var ctx = c.getContext("2d");
//Fill the path
ctx.fillStyle = "#ffffff";
ctx.fillRect(0,0,w,h);
var img=document.getElementById("persphoto");
ih=parseInt(document.getElementById("persphoto").getAttribute("height"));
iw=parseInt(document.getElementById("persphoto").getAttribute("width"));
var maxw = 150;
var maxh = 150;
if (ih > iw) {
var newh = 150;
var neww = Math.round(150 * (iw / ih));
} else if (ih < iw) {
var newh = Math.round(150 * (ih / iw));
var neww = 150;
} else {
var newh = 150;
var neww = 150;
}
var newx = Math.round((296 - neww) / 2);
var newy = 60 + Math.round((150 - newh) / 2);
img.onload = function() {
ctx.drawImage(img,newx,newy,neww,newh);
};
ctx.fillStyle = "#000000";
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText(document.getElementById("persname").value, w/2, h*0.65);
ctx.fillText(document.getElementById("adress").value, w/2, h*0.69);
ctx.fillText(document.getElementById("postaddr").value, w/2, h*0.73);
ctx.fillText(document.getElementById("homephone").value, w/2, h*0.77);
ctx.fillText(document.getElementById("cellphone").value, w/2, h*0.81);
var canvasData = c.toDataURL("image/png");
/*
document.getElementById("canvasdata").value = canvasData;
document.getElementById("hidepersphoto").value = document.getElementById("persphoto").value;
document.getElementById("hidepersname").value = document.getElementById("persname").value;
document.getElementById("hideadress").value = document.getElementById("adress").value;
document.getElementById("hidepostaddr").value = document.getElementById("postaddr").value;
document.getElementById("hidehomephone").value = document.getElementById("homephone").value;
document.getElementById("hidecellphone").value = document.getElementById("cellphone").value;
*/
}
My problem is as I said that when I call convertCanvasToImage any images currently on the canvas doesn't get converted. The result is:
Can anyone spot where the problem is?

Few Changes:
pass the string literal "canvasresult" of canvasId rather than a variable.
<script type="text/javascript"> convertCanvasToImage("canvasresult"); </script>
Get the canvas object based on the Id:
// Converts canvas to an image
function convertCanvasToImage(canvasId) {
var image = new Image();
var canvas=document.getElementById(canvasId);
image.src = canvas.toDataURL("image/png");
//return image;
document.getElementById("wrap1").appendChild(image);
}

Related

How to convert textarea text into canvas image by using javascript?

I am trying to convert my textarea text into canvas image. that text needs to be displayed in canvas as an image. But sometimes my text is perfectly showing in canvas but the sentences are breaking into words and switching to the next lines. Line breaks are occuring due to which sentences are in improper format. I want to display the text in my textarea and in my canvas in a wrap format. In my below code i am not getting any output . Please advise with best.
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<form id="myForm">
Text: <input id="myText" placeholder="your text"/>
<br />
<input type="submit" value="submit" />
</form>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, 0, 0);
}
imageObj.src = "https://image.freepik.com/free-vector/abstract-background-in-geometric-style_1013-
17.jpg";
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
var text = document.getElementById('myText').value;
if(text.length == 0)
{
alert("you forgot to put something");
}
else
{
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var maxWidth = 400;
var lineHeight = 25;
var x = (canvas.width - maxWidth) / 2;
var y = 60;
var text = document.getElementById("myText").value;
context.font = "16pt Calibri";
context.fillStyle = "#333";
context.fillText(text, 50, 50);
wrapText(context, text, x, y, maxWidth, lineHeight);
e.preventDefault();}
});
</script>
</body>
You can use html2canvas for this purpose.

Write custom text on mug from user by keyboard by Javascript, Html5

I want to write text on mug.And change property like font-style, color, size by Javascript, Html5. Right now i am using Javascript, Html5.
I want to write text on this mug image and also want to change font color, font-size, font style and rotate text.
I seen this link but i am not satisfied.
How can I write text on a HTML5 canvas element?
I can't give you original code. I have a sample code for this page.
HTML CODE:
<body>
<canvas id="canvas"></canvas>
</body>
JAVASCRIPT CODE:
$(function () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var productImg = new Image();
productImg.onload = function () {
var iw = productImg.width;
var ih = productImg.height;
console.log("height");
canvas.width = iw;
canvas.height = ih;
ctx.drawImage(productImg, 0, 0, productImg.width, productImg.height,
0, 0, iw, ih);
//start();
// outline
ctx.beginPath();
ctx.moveTo(88, 235.734375);
ctx.bezierCurveTo(88, 234.734375, 204, 298, 327, 234.734375);
ctx.stroke();
};
productImg.src = "https://d2z4fd79oscvvx.cloudfront.net/0018872_inspirational_teacher_mug.jpeg";
var img = new Image();
img.onload = start;
img.src = "http://blog.foreigners.cz/wp-content/uploads/2015/05/Make-new-friends.jpg";
var pointer = 0;
function start() {
var iw = img.width;
var ih = img.height;
var xOffset = 125,
yOffset = 122;
var a = 122.0;
var b = 30.0;
var scaleFactor = iw / (2*a);
// draw vertical slices
for (var X = 0; X < iw; X+=1) {
var y = b/a * Math.sqrt(a*a - (X-a)*(X-a)); // ellipsis equation
ctx.drawImage(img, X * scaleFactor, 0, 6, ih, X + xOffset, y + yOffset, 1, ih - 605 + y/2);
}
}
});
I am only using Javascript, Html5. I have seen this link http://varunpes.net46.net/Fancy_Product_Designer_V3.0.7/example/cust-txt.jsp
But this plugin have use in Php. I don't want this functionality in Php.
Anybody have any idea please share with me. If Any body have different idea than also share with me.
Write custom text in canvas with fabric js library.
var canvas = new fabric.Canvas('canvas');
$('#font').change(function(){
var obj = canvas.getActiveObject();
if(obj){
obj.setFontFamily($(this).val());
}
canvas.renderAll();
});
function addText() {
var oText = new fabric.IText('Tap and Type', {
left: 100,
top: 100 ,
});
canvas.add(oText);
canvas.setActiveObject(oText);
$('#fill, #font').trigger('change');
oText.bringToFront();
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<div class="container">
<div class="row">
<div class="col s12">
<button class="btn" onclick="addText()">Add Custom Text</button>
<select class="browser-default" id="font">
<option>arial</option>
<option>tahoma</option>
<option>times new roman</option>
</select>
<br />
<canvas id="canvas" width="750" height="550" style="border:1px solid #333"></canvas>
</div>
</div>
</div>

Browser crashes when taking picture with camera

I've got a simple page that allows you to take a picture with your phone and then upload it to the server.
To achieve that, I'm using HTML5's input as file, so when I click (or tap on) Choose File two options are displayed:
Use the phone's camera (I'm using an iPhone with iOS8)
Select a picture from the library.
If I select the picture from the library everything works just fine, as for now I'm only displaying it on screen, but if I use the camera, after taking the picture the browser crashes. I haven't been able to debug because it never hits my breakpoints since the debugging session crashes as well.
Here's the code. Any help will be highly appreciated.
<!--Seg:openPage-->
<script>
function resizeImg(img, canvas, ctx){
var MAX_WIDTH = 500;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
alert(width + " " + height);
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
//var ctx = canvas.getContext("2d");
//var dataURL = canvas.toDataURL(img, 0.5);
//img.src = dataURL;
ctx.drawImage(img, 0, 0, width, height);
}
function drawOnCanvas(file) {
var reader = new FileReader();
reader.onload = function (e) {
var dataURL = e.target.result;
var c = document.querySelector('canvas');
var ctx = c.getContext('2d');
var img = new Image();
img.src = dataURL;
//****img.onload = function() {
//c.width = 200; //img.width;
//c.height = 200; //img.height;
if (img.complete) {
resizeImg(img, c, ctx);
//ctx.drawImage(img, 0, 0);
} else {
img.onload = function () {
resizeImg(img, c, ctx);
//ctx.drawImage(img, 0, 0);
};
}
//ctx.drawImage(img, 0, 0);
//****};
//****img.src = dataURL;
};
reader.readAsDataURL(file);
}
function upload(file){
var encodedB64 = window.btoa(file);
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend=function(){
if(file){
//reader.readAsDataURL(file);
console.log(reader);
//alert(reader.result);
$('.output').val(reader.result);
}
submit_form('f','GO');
}
}
$(document).ready(function(){
var input = document.querySelector('input[type=file]');
input.onchange = function () {
var file = input.files[0];
//upload(file);
drawOnCanvas(file);
//displayAsImage(file);
};
});
</script>
<style>
/**
#canvas-container {
width: 100%;
height: 100%;
}
#canvas-container #myCanvas{
width: 100%;
}**/
</style>
<div class="container" style="padding-top: 10px;">
<div id="page_content">
<form name="f" method="POST" action="#&PGM " class="sigPad">
<input type="hidden" name="output" class="output">
<!--Add file input-->
<p>Choose a picture from your device or capture one with your camera now:</p>
<input type="file" id="picManager" accept="image/*" capture="camera">
<!--Add canvas-->
<p>Photo:</p>
<div id="canvas-container">
<canvas id="myCanvas"></canvas>
</div>
<button type="submit" class="btn btn-primary">View</button>
</form>
</div>
</div>
<!--End:openPage-->

canvas image size in html5

var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.src = document.getElementById("tempImg").src;
imageObj.onload = function () {
var x = 188;
var y = 30;
var width = 200;
var height = 137;
context.drawImage(imageObj, x, y, width, height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
<canvas id="canvasPnl" width="132" height="120" style="border:0px solid #d3d3d3;"></canvas>
The size of the image is becoming bigger and it is not fitting in canvas and also the image is rotated.
How to get original image in canvas?
Ok, take a look at your reworked code below.
Notice "imageObj.src = document.getElementById("tempImg").src;" must go after imageObj.onload.
I have no access to your locationtxt or your tempImg, so I assume you are sure they are not the source of your problem.
This line of code will take an image of ANY size and force it to fit in your specified canvas size by scaling it. When it scales, you may get image distortion if your canvas size is not proportional to your image size.
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
Here is your code -- just modified a bit :)
var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
imageObj.src = document.getElementById("tempImg").src;
<html>
<head>
<title></title>
</head>
<style type="text/css">
#mycanvas
{
border: 1px solid black;
}
</style>
<script type="text/javascript">
window.addEventListener('load', function () {
var img = new Image, ctx = document.getElementById('myCanvas').getContext('2d');
var img1=new Image;
img.src = 'ship.png';
img1.src='3D025.jpg';
img.addEventListener('load', function () {
var width = img.naturalWidth; // this will be 300
var height = img.naturalHeight; // this will be 400
var interval = setInterval(function() {
var x = 260, y = 0;
return function () {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img1, 0, y);
ctx.drawImage(img, x, 300,width,height);
x += 1;
if (x > ctx.canvas.width) {
x = 260;
width=width-10;
height=height-10;
ctx.drawImage(img, x, 300,width,height);
}
if (x == 750) {
x = 260;
}
};
}(), 1000/40);
}, false);
}, false);
</script>
<body>
<canvas id="myCanvas" height="600" width="1000"></canvas>
</body>
</html>

FileReader.js nothing happens in IE9

I need help setting up Jadriens FileReader.js. I have set up everything as I think this polyfill works. But the callback that fires when everything is initiated doesn't fire in IE9. This is my markup:
<body>
<div class="main">
<canvas id="mainCanvas" width="600" height="600"></canvas><br />
<div id="fileReaderSWFObject"></div>
<input type="file" id="imageLoader" name="imageLoader" /><br />
<input id="text" type="text" placeholder="some text...">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script>
<!--[if lt IE 10]>
<script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="js/vendor/jquery-ui-1.8.23.custom.min.js"></script>
<script src="js/vendor/jquery.FileReader.min.js"></script>
<![endif]-->
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
</body>
And this is main.js:
$(function () {
// Variables
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
var canvasCenter = canvas.width / 2;
var img = '';
var newImageHeight = 0;
var logoX = 0;
var padding = 50;
// Functions
var flushCanvas = function () {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.width + padding);
if (img !== '') {
context.drawImage(img, padding, padding, canvas.width - (padding * 2), newImageHeight - (padding * 2));
}
setText();
};
var setText = function () {
context.textAlign = 'center';
context.fillStyle = '#fff';
context.font = '22px sans-serif';
context.textBaseline = 'bottom';
context.fillText($('#text').val(), canvasCenter, canvas.height - 40);
};
// Init
if ($.browser.msie && $.browser.version <= 9) {
swfobject.embedSWF('filereader.swf', 'fileReaderSWFObject', '100%', '100%', '10', 'expressinstall.swf');
$('#imageLoader').fileReader({
id: 'fileReaderSWFObject',
filereader: 'filereader.swf',
expressInstall: 'expressInstall.swf',
debugMode: true,
callback: function () { console.log('filereader ready'); }
});
}
$('#imageLoader').change(function (e) {
if ($.browser.msie && $.browser.version <= 9) {
console.log(e.target.files[0].name);
} else {
var reader = new FileReader();
reader.onload = function (event) {
img = new Image();
img.onload = function () {
newImageHeight = (img.height / img.width) * (canvas.width);
canvas.height = newImageHeight + padding;
flushCanvas();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});
$('#text').keyup(function (e) {
flushCanvas();
});
});
A lot of code but i thought a context might help. The important lines are just below the Init comment. The callback-function in the .fileReader init options never fires. It does fire in other modern browsers though (if you remove the if statement).
There are a combination of mistakes here.
Jahdriens filereader takes care of the embedding of flash. Just include the swfObject library.
Browser sniffing = bad idea. Modernizr = good idea.
Make sure you have flash for IE installed :(
My final code looks like this and it works perfect. HTML:
<canvas id="mainCanvas" width="600" height="600"></canvas><br />
<a id="imageLoaderButton" class="button upload">load image</a>
<input type="file" id="imageLoader" class="hidden" name="imageLoader" />
<input id="text" type="text" placeholder="some text...">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script>
<script src="js/main.js"></script>
+ link in a custom build of modernizr in the head. (click "non core detects" -> "file-api" when creating you custom build)
And my JS:
$(function () {
Modernizr.load({
test: Modernizr.filereader,
nope: ['js/vendor/swfobject.js', 'js/vendor/jquery-ui-1.8.23.custom.min.js', 'js/vendor/jquery.FileReader.min.js'],
complete: function () {
if (!Modernizr.filereader) {
$('#imageLoaderButton').fileReader({
id: 'fileReaderSWFObject',
filereader: 'filereader.swf',
expressInstall: 'expressInstall.swf',
debugMode: true,
callback: function () {
$('#imageLoaderButton').show().on('change', read);
}
});
} else {
$('#imageLoaderButton').show().on('click', function () {
$('#imageLoader').trigger('click').on('change', read);
});
}
}
});
// Variables
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
var canvasCenter = canvas.width / 2;
var img = '';
var padding = 50;
// Functions
var flushCanvas = function () {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.width + padding);
if (img !== '') {
context.drawImage(img, padding, padding, canvas.width - (padding * 2), newImageHeight - (padding * 2));
}
setText();
};
var setText = function () {
context.textAlign = 'center';
context.fillStyle = '#fff';
context.font = '22px sans-serif';
context.textBaseline = 'bottom';
context.fillText($('#text').val(), canvasCenter, canvas.height - 40);
};
var read = function (e) {
if (typeof FileReader !== 'undefined') {
var reader = new FileReader();
reader.onload = function (event) {
img = new Image();
img.onload = function () {
newImageHeight = (img.height / img.width) * (canvas.width);
canvas.height = newImageHeight + padding;
flushCanvas();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
};
$('#text').keyup(function (e) {
flushCanvas();
});
});
The problem with IE9 is you need flash player to be installed first also there are many features not supported by IE9

Categories