Canvas datatoURL not saving canvas content - javascript

I am trying to use toDataURL in Html5 Canvas to export an image to a PNG file in a new window.
Here's my JS code (I think you guys need to see it all to check if there's something wrong)
var oCtx;
var oCanvas;
var img;
var oImg;
function updateClicked() {
oCanvas.width = oCanvas.width;
oCtx.drawImage(img,0,0);
oCtx.font = "normal 23px arial"; // different font
oCtx.textBaseline = "top"; // text baseline at the top
oCtx.fillStyle = "#666";
oCtx.fillText(document.getElementById("attentionde").value, 255, 365);
oCtx.font = "bold 28px arial"; // different font
oCtx.fillStyle = "red";
oCtx.fillText(document.getElementById("nofacture").value, 172, 226);
}
// setup our test canvas
// and a simple drawing function
window.onload = function() {
oCanvas = document.getElementById("thecanvas");
oCtx = oCanvas.getContext("2d");
var iWidth = oCanvas.width;
var iHeight = oCanvas.height;
img=new Image();
img.src="Fond_Facture_Medio.jpg"; //My background image source
//BACKGROUND-IMAGE//
img.onload = function(){
oCtx.drawImage(img,0,0);
};
var dataUrl = oCanvas.toDataURL();
var button = document.getElementById("thebutton");
button.onclick =function() {
window.open(dataUrl, "toDataURL() image", "width=1275, height=1650");
}
}​
When I click on my button (id="thebutton")...it does open a new window with a PNG file in it, but the png is blank...Seems like it does not get the images drawn in the Canvas for a unknown reason.
I tried adding this code right before the var dataUrl = oCanvas.toDataURL(); line :
oCtx.fillStyle = "rgba(0, 0, 255, .5)";
oCtx.fillRect(25, 25, 125, 125);
Just to test if I was drawing a shape, it would save it through the dataURL process.
When I tested it, by clicking on the "thebutton" button, it opened a new window, and voila! I was able to see and save the canvas image with a light-blue rectangle in it...but no backgroud-image, and no text...nothing else. I really don't understand what's wrong. Thank you!

Move this line
var dataUrl = oCanvas.toDataURL();
inside the button.onclick handler.
At the moment you create the data URL, neither the window element nor any img element fired its load event, so nothing has been drawn.

Related

Can't seem to get an old image off the canvas

I'm importing an image (that has to come in portrait) onto a canvas object, rotating it (because it's actually landscape) and running some OCR on the base64 from the canvas. That all works fine. However when I put a new image onto the canvas, the old one is retained and never replaced. I've tried clearRect, even gone to the extent of creating a new dom element each time and destroying it when I have everything I need (which is still in the code below) but I just cannot get the first image to clear.
Here's the relevant bit of the code
function onSuccess(imageURI) {
//CREATE NEW CANVAS ELEMENT
g = document.createElement('canvas');
g.setAttribute("id", "thePic");
g.style.overflow = "visible";
document.body.appendChild(g);
const canvas = document.getElementById('thePic'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = imageURI;
base_image.onload = function(){
const uriheight = base_image.naturalHeight;
const uriwidth = base_image.naturalWidth;
console.log(uriwidth + " " + uriheight);
context.canvas.width = uriheight;
context.canvas.height = uriheight;
context.drawImage(base_image, 0, 0);
//ROTATE THE IMAGE 90
context.clearRect(0,0,canvas.width,canvas.height);
context.save();
context.translate(canvas.width/2,canvas.height/2);
context.rotate(90*Math.PI/180);
context.drawImage(base_image,-base_image.width/1.2,-base_image.width/1.2);
context.restore();
var theCanvas = document.getElementById('thePic');
var rotImg = theCanvas.toDataURL();
var rotImg = rotImg.substring(21);
textocr.recText(4, rotImg, onSuccess, onFail);
function onSuccess(recognizedText) {
var recdata = recognizedText.lines.linetext;
var blockData = recognizedText.blocks.blocktext;
context.clearRect(0, 0, 10000,10000);
base_image = "";
rotImg = "";
document.getElementById('thePic').outerHTML = "";
document.getElementById('cgh').innerHTML = "";
}
}
}
Any advice much appreciated.
So it turned out to not be the canvas at all, it was image caching in a previous function that give the image to the canvas.
Thanks to everyone who took the time to have a squiz.

Why is this appearing behind the canvas instead of drawing over it?

I am working on a dynamic web map with HTML5 and canvas.
I loaded the map in PNG format, but whenever I try to draw on it, it draws behind the map like this:
I need it to draw over the white squares.
This is my code:
window.onload = function() {
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "img/plano.png"; //transparent png
ctx.fillRect(1039, 150, 50, 50);
}
Thanks in advance!
The fillRect needs to happen after the image has loaded. The image loads asynchronously so the only safe place for this to happen is after the drawImage...
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillRect(200,200,50,50); // Draw rect after image
}

How to determine if image is using transparency on Javascript?

I'd like to be able to detect if a logo type image has a transparent background or not, let's imagin that two similar images are .png files but one has a white background and another on has a transparent background, how would I be able to determine the one with transparency ?
I've tried using colorthief but it doesn't take transparency into account, so I thought doing it by myself on canvas. A first solution would be to convert the png file into jpg and if the background color of the jpg after being converted appear to be black then it's a transparent logo, but this might be a problem for users with black background and white logos. Is there a better solution than that ?
http://jsfiddle.net/9s5qf5cu/
from png to jpg :
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
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 = 100;
canvas.height = 100;
ctx.drawImage(img,0,0, 100, 100);
document.getElementById("image").src = canvas.toDataURL("image/jpeg");
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
Use this function by passing your context and your canvas. Then it will loop over the alpha channel until it finds an entry that is not completely opaque.
function hasAlpha (context, canvas) {
var data = context.getImageData(0, 0, canvas.width, canvas.height).data,
hasAlphaPixels = false;
for (var i = 3, n = data.length; i < n; i+=4) {
if (data[i] < 255) {
hasAlphaPixels = true;
break;
}
}
return hasAlphaPixels;
}
Note: this will not work if your canvas is tainted.

How to Save text over image with jquery

I am new to javascript. i have the following code of javascript and html. the problem is that when i download the image the text written by the javascript dose not show on the downloaded image. or you can say in other words the text dose not print on the image. which i want to achieve.
following is the code
<script type="text/javascript">
jQuery(function($){
var textover_api;
$('#target').TextOver({}, function() {
textover_api = this;
});
});
</script>
<img src="demo.jpg" id="target" />
i want to achieve the functionality like http://addtext.com/.
thanking in advance.
You can make use of HTML5 using canvas and return the base64 data example here:
Source:Javascript; Adding text on image using canvas and save to image
draw();
function draw() {
var canvas = document.getElementById('idCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.font = "40px Calibri";
context.fillStyle = "red";
context.fillText("My TEXT!", 50, 300);
var canvas = document.getElementById('idCanvas');
var dataURL = canvas.toDataURL();
alert(dataURL);
}
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.src = "http://lorempixel.com/400/200/";
};`
<canvas id="idCanvas" width="576" height="577"></canvas>
http://jsfiddle.net/hmr7c8po/

Javascript; Adding text on image using canvas and save to image

i just want to make a page where u can type a text and add it on selected image and save that as new image.
I tried to do it in few ways, but without luck.
<body>
<canvas id = "idCanvas" width = "576" height = "577"> </canvas>
<img id="canvasImg" width = "576" height = "577"></img>
<script>
window.onload = function(){
var canvas = document.getElementById('idCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var dataURL = canvas.toDataURL();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0, 576, 577);
context.font = "20px Calibri";
context.fillText("My TEXT!", 50, 200);
document.getElementById('canvasImg').src = toDataURL();
window.alert(dataURL);
};
imageObj.src = "image.png";
};
</script>
When i use toDataURL() in img src, the image won't be displayed, it only works if i'm not using drawImage in canvas.
Ok so yes it will not work for security reason, but there is a solution.
See here a working demo: FIDDLE
draw();
function draw() {
var canvas = document.getElementById('idCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.font = "40px Calibri";
context.fillStyle = "red";
context.fillText("My TEXT!", 50, 300);
var canvas = document.getElementById('idCanvas');
var dataURL = canvas.toDataURL();
alert(dataURL);
}
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.src = "https://loremflickr.com/400/200";
};
First of all, Should it be canvas.toDataURL() ?
Here is a similar example with getting contents into image element http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/
Also I was getting the following error when image is loaded from another hostname:
Uncaught SecurityError: Failed to execute 'toDataURL' on
'HTMLCanvasElement': Tainted canvases may not be exported.
When image is not added to canvas it works fine, so issue could be related to CORS HTTP headers not added with image. Try removing
context.drawImage(imageObj, 0, 0, 576, 577);
to see that it works without image
Here is a demo based on code in question.
http://jsbin.com/logikuwefo/1/edit

Categories

Resources