I have HTML canvas and it work fine to display image.
And I have this jquery code to download the image :
$(".img-download").click(function(){
var data = canvas.toDataURL();
download.href = data; -- I tried this to download image, but PNG file generated cannot be opened in photoshop or any other image manipulation apps
alert (data); -- then, I tried to see what's actually the data content
});
And here's my download button :
Download
Here's what the data content :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjAAAAH0CAYAAAAjYBdQAAAgAElEQVR4XrS9d7Cm6Vnm93Sf0DlMTp0naZSFTCokYNf2er2mbBZvFcG4WGxClQtThVibUpk/EFCLjQoEJmgUkECkrRImLMqiKEmIIIE0EsrSaKIm9/R0DqfP6fb1u677ft9vpJGE7Nqv58w53/e97xPu5w7XHZ7n3fSrv/rblzdt2jzys2lsbKyPy5suD16X9WvT2DyWNm8em/WT1yW+GZs36a/Ll/QXf2/yvZcv5T7uujT9vVnt6WL9LC/pzkvr4+LauXHu7Olx/vxpt7Okpi9d2lB/G2lf/V9W5xuXLo3N+vKy2qNNfjbWL42lpSX/MED6vKzrGIcG6b8Z3yY1TBvctbx5eawzL413WR/Q58rW1bFtxw5dR/uZg+9byn28mPP6+rr/XmIcG/pedPLXvp5xp2/aps/QSWPf2DDdGLPpwk2Mx9MwYUMzN3bZ7fC+vpjm6zXQ55sZtNYia+JWTR/ebFZ7lzZ0v77XSrh9+qflzZtFJ415aWnZffV85vWk+9Dssm7lms36Y/OmpbFrx65x1dXXjOUtq15r+twsuq+vb4wTJ06MCxcujJ07d+hn59gmerImyysr7tN9aU039MPvZfXP2OAvj19jUqPVt9ZoZXXs3rt3bN22bZw4eXI8dfwpX3uJ8XC9aE9/58+fdz9bt24ND7it8FfIDIHCrxsaM/0v+f2SyJI1oM26JRRjLPpv06ZL4r5L4pWN0JzPWWOuh59MUfGxaAOx6MNcU/wCDTOerNNl+vXa5Tro7DH4ojG2bN0ydu/eM5aXV8fpM2fGGf2wjh4jvK8+t4r220STVdOXdjMG5Gvt4vo4d+68aRL+GKKZZoBcqK8lfdY0siyUjCIjfG5R0Yu/a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it can't be opened? why the PNG file is corrupt?
UPDATE : here's my complete jquery script
$(".pepe-thumbnail").click(function(){
var pepe_src = $(this).attr("src");
$("#canvasimg").attr("src", pepe_src);
});
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var deviceWidth = window.innerWidth;;
canvasWidth = deviceWidth - 40;
canvasHeight = deviceWidth - 40;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
if (canvas.width > 500 || canvas.height > 500){
canvas.width = 560;
canvas.height = 500;
}
var img = document.getElementById("canvasimg");
//imgx = canvas.width/2 - img.width/2;
//imgy = canvas.height/2 - img.height/2;
imgx = 0;
imgy = 0;
function runLoop(){
ctx.lineWidth = 8;
ctx.font = "26pt Lato";
ctx.strokeStyle = "black";
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.lineJoin = "round";
var text1 = document.getElementById("canvastext-top").value;
//text1 = text1.toUpperCase();
var text2 = document.getElementById("canvastext-bottom").value;
//text2 = text2.toUpperCase();
x = canvas.width/2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, imgx, imgy, canvas.width, canvas.height);
ctx.strokeText(text1, x, 50);
ctx.fillText(text1, x, 50);
ctx.strokeText(text2, x, (canvas.height - 40));
ctx.fillText(text2, x, (canvas.height - 40));
window.setTimeout(runLoop, 14);
};
runLoop();
$(".img-download").click(function(){
var data = canvas.toDataURL();
alert (data);
});
Try this :
$(".img-download").click(function(){
var data = canvas.toDataURL();
$(this).attr("href",data)
$(this).attr("download","imgName.png");
});
Ref:Download canvas image using JS Jquery
var data = canvas.toDataURL();
dataURL = data.replace(/^data:image\/[^;]*/, 'data:application/octet-stream');
dataURL = dataURL.replace(/^data:application\/octet-stream/, 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=Canvas.png');
var aTag = document.createElement('a');
aTag.download = 'download.png';
aTag.href = dataURL;
aTag.click();
Related
I am trying to crop an image with Javascript. I have croppr.js and it is sending the data and I was trying to crop the image so I can save it to a storage server with Base 64. I have read online about .drawimage(). I have tried:
function process(data) {
console.log("DATA:" + data)
var canvas = document.getElementById("canvas")
var context = canvas.getContext('2d');
var imageObj = new Image();
var zoom
imageObj.onload = function() {
context.width = data.width
context.height = data.height
// draw cropped image
var sourceX = data.x;
var sourceY = data.y;
var sourceWidth = data.width / 2;
var sourceHeight = data.height / 2;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = 0;
var destY = 0;
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
var dataurl = canvas.toDataURL('image/jpeg', 1.0)
console.log(dataurl)
};
imageObj.src = document.getElementsByTagName("img")[0].src;
console.log(imageObj.src)
}
data Contains X Y Height Width As an JSON array.
First I see is the:
context.width = data.width
context.height = data.height
Did you meant to do canvas instead?
Here is an example:
function process(data) {
var canvas = document.getElementById("canvas")
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
canvas.width = data.width
canvas.height = data.height
// draw cropped image
var w = data.width / 2;
var h = data.height / 2;
context.drawImage(img, data.x, data.y, w, h, 0, 0, w, h);
};
img.src = data.src;
}
process({x:0, y:0, width:600, height: 600, src: "http://i.stack.imgur.com/UFBxY.png"})
<canvas id="canvas"></canvas>
That is the only issue I could see on your code.
What is not clear is the data you use to call the process function
I got an image, it could be of every size but I need to take the center area of 86x86. Also I've to do that in javascript when a new image is loaded, replacing the old one.
At the end of the code I need to have my 's src updated with the new image.
function loadedImage(elem,gCount){
var crop = { //just messing with numbers
top : 10,
left : 10,
right : 20,
bottom : 20,
};
var file = elem.files[0]; //I take the loaded image
var img = document.getElementsByName('imag')[gCount]; //I take the interessed <img>
var canvas = document.createElement("canvas"); //create canvas
canvas.width = crop.right - crop.left; //set dimensions
canvas.height = crop.bottom - crop.top;
var ctx = canvas.getContext("2d"); // so we can draw
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.width = img.width;
image.height = img.height;
image.src = window.URL.createObjectURL(file);
ctx.drawImage(image, -crop.left, -crop.top);
image.src = canvas.toDataURL("image/png");
img.src = image.src;
}
No image is shown
Use a load event listener to wait for your image to load. Once it's ready, you can then start drawing.
To draw the center part of your image, the source x-coordinate should be half the width of your image, minus half the width of the crop. (The source y-coordinate can be calculated in a similar way.)
var input = document.getElementsByName('input')[0];
input.addEventListener('change', function (e) {
var file = e.target.files[0];
drawCroppedImage(file, 86, 86);
});
function drawCroppedImage(file, w, h) {
var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function (e) {
var sx = (image.width / 2) - (w / 2), // Source X
sy = (image.height / 2) - (h / 2), // Source Y
dx = 0, // Destination X
dy = 0; // Destination Y
ctx.drawImage(image, sx, sy, w, h, dx, dy, w, h);
});
image.src = URL.createObjectURL(file);
}
<input type="file" name="input">
<br><br>
<canvas id="canvas" width="86" height="86"></canvas>
I am new here, so please be consider.
I've created a new canvas and created a rects in the canvas , when I set a background to the canvas I have a terrible problem that The background is on the shapes
Here is the code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var background = new Image();
background.src = "url_to_image";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
<canvas id="canvas" width=450 height=700></canvas>
Thanks
Edit:
I found in my code a function of fillStyle that change my background,
so I delete it and instead of this I put this:
var w = canvas.width;
var h = canvas.height
var img = new Image();
img.src = "http://www.girija.info/wp-content/uploads/2015/08/Paznja-Sabranost-450x700.png";
img.onload = function () {
var pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, w, h);
};
//ctx.fillStyle = "#FAF7F8";
rect(0, 0, WIDTH, HEIGHT);
// redraw each rect in the rects[] array
for (var i = 0; i < rects.length; i++) {
var r = rects[i];
ctx.fillStyle = 'red';
rect(r.x, r.y, r.width, r.height);
}
But every drag of the rect (the rects loaded from stack and can be draggable) the background color of the rect change
You can set the background using the css property
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BB = canvas.getBoundingClientRect();
var offsetX = BB.left;
var offsetY = BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
ctx.rect(10, 10, 100, 100);
ctx.fill();
canvas.style.backgroundImage = 'url(https://picsum.photos/450/700)';
<canvas id="canvas" width=450 height=700></canvas>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
background_image();
function background_image()
{
background_image = new Image();
background_image.src = 'https://image.ibb.co/kmV8kz/photodune_2359510_smiles_l_22.png';
background_image.onload = function(){
context.drawImage(background_image, 0, 0);
}
}
<canvas id="canvas" width=450 height=700></canvas>
I have a Javascript function that create a canvas, write a image and a text on it. At the and I need the base64 dataUrl but what I get is only a blank canvas.
This is my function:
function createBreadCrumb(label) {
var canvas = document.createElement('canvas');
canvas.width = 25;
canvas.height = 30;
var img = new Image;
img.src = 'map-pin-breadcrumb.png';
var ctx=canvas.getContext("2d");
img.onload = function(){
ctx.drawImage(img, 0, 0);
ctx.font = "11px Arial";
ctx.textAlign="center";
ctx.fillText(label, 12, 16);
};
return canvas.toDataURL();
}
You are calling toDataURL before the image is loaded. As a result, none of your canvas instructions have run yet. Because the image is loaded asynchronously, you cannot get the resulting canvas synchronously and must use a callback or a promise.
Try this.
function createBreadCrumb(label, callback) {
var canvas = document.createElement('canvas');
canvas.width = 25;
canvas.height = 30;
var img = new Image;
var ctx = canvas.getContext("2d");
img.onload = function(){
ctx.drawImage(img, 0, 0);
ctx.font = "11px Arial";
ctx.textAlign="center";
ctx.fillText(label, 12, 16);
callback(canvas.toDataURL());
};
img.src = 'map-pin-breadcrumb.png';
}
createBreadCrumb("hello", function(crumb){
// do your stuff
});
I got this script:
function capture(video, scaleFactor) {
if(scaleFactor == null){
scaleFactor = 1;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
return canvas;
}
function shoot(){
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
canvas.onclick = function(){
window.open(this.toDataURL());
};
snapshots.unshift(canvas);
output.innerHTML = '';
for(var i=0; i<1; i++){
output.appendChild(snapshots[i]);
}
}
What I want to do is export the snapshot to a bitmap image. I read that I could use this line:
canvas.toDataURL('image/jpeg');
But I don't know where to add it.
Any ideas?
ctx.drawImage(video, 0, 0, w, h);
canvas.toDataURL(...)
toDataURL will return you a string which is usually base64 encoded image (file) content. You can display it in image tag by < img src="the string"/>. Or you can use javascript to do whatever you want...
Pass it to window.open
canvas.onclick = function () {
window.open(canvas.toDataURL('image/png'));
};
Full Example : http://www.nihilogic.dk/labs/canvas2image/