I'm having a problem with retrieving the base64 version of an image displayed on a canvas. I've looked at the other questions but none of the solutions including canvas2image seem to work.
Here's my code:
<!DOCTYPE>
<html>
<head>
<style>#canvas {cursor: pointer;}</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'http://sstatic.net/stackoverflow/img/newsletter-ad.png';
can.onclick = function() {
ctx.translate(img.width-1, img.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
};
document.write(can.toDataURL()); //isn't writing the correct base64 image
</script>
</body>
</html>
Here's the test link: http://jsfiddle.net/mrchief/hgTdM/1/ thanks, Mrchief
What I need is the correct base64 output of the image in the canvas.
The problem is that it won't output the correct base64 version of the image.. But as you can see, the image inside the canvas is displayed without any problems.
I've tested it on chrome & firefox
Thanks very much..
Your document.write() call occurs immediately upon page load, before your img is loaded and drawn and before your onclick handler can ever run. You need to wait to generate the data URI until after everything has finished happening to the canvas.
Ignoring the onclick, here's something that writes out the data url after the image has loaded and been drawn to the canvas in a rotated fashion:
<!DOCTYPE html>
<html><head>
<title>Rotated Image Data URL</title>
<style type="text/css" media="screen">
canvas, textarea { display:block }
</style>
</head><body>
<canvas id="canvas"></canvas>
<textarea id="data" rows="20" cols="80"></textarea>
<img id="echo">
<script type="text/javascript">
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.translate(img.width-1, img.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
var url = document.getElementById('data').value = can.toDataURL();
document.getElementById('echo').src = url;
}
img.src = 'gkhead.jpg';
</script>
</body></html>
You can see this demo in action here: http://phrogz.net/tmp/upside-down-image-url.html
Note that the image you load must be on the same domain as your script, or else you will not be allowed to create the data URL.
Related
i am a newbie to programming,
I have an HTML code for displaying base64 image the image is dynamic link, always come with different sizes
I need to resize that image and create preview mode with smaller image with an aspect ratio
ex:
my original image on html are 600x300 I need to preview it 300x150
my original image HTML are 1000x500 I need to preview 500x250
I have a javascript for resizing but can't figure out how to get image base64 from my HTML code
Please who can give me some help on these to archive my goal
I cant paste HTMl code here because is to long please check HTMl on codepin
https://codepen.io/Gilavani/pen/JjLXBOb
function resizedataURL(datas, wantedWidth, wantedHeight)
{
// We create an image to receive the Data URI
var img = document.createElement('img');
// When the event "onload" is triggered we can resize the image.
img.onload = function()
{
// We create a canvas and get its context.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions at the wanted size.
canvas.width = wantedWidth;
canvas.height = wantedHeight;
// We resize the image with the canvas method drawImage();
ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);
var dataURI = canvas.toDataURL();
/////////////////////////////////////////
// Use and treat your Data URI here !! //
/////////////////////////////////////////
};
// We put the Data URI in the image's src attribute
img.src = datas;
}
Thanks you in Advice
Best Regards
let srcImg = document.getElementById("orignal").src;
let prev = document.getElementById("preview");
function resizedataURL(datas, wantedWidth, wantedHeight)
{
prev.src = datas;
prev.onload = function()
{
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = wantedWidth;
canvas.height = wantedHeight;
ctx.drawImage(this, 0, 0, wantedWidth, wantedHeight);
prev.src = canvas.toDataURL();
};
}
resizedataURL(srcImg, 150,150);
<html>
<body>
<img id="orignal" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAAAXNSR0IArs4c6QAAFSpJREFUeF7tnTuLZcUWgGtAZJykYRR0EAykwcBAEDM18h+YGPiIBEFREMxE8fEDBPGBgpEPMHByYzWbxEyh6UhnDHTAZJysZZ+Z3XP69Dm9a+9aVbUe3yTXvl2Ptb611nf3PnPuveeuXLlydPHixXT+/PnEHwhAAAIaCdy8eTNdv349nTs8PDwa/mF/fz/t7e1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0vIYNT0rjK+AcYQ1r1yW46wP5UVwPPvjgSlpnSXB4Bfzqq6/Syy+/nB599NH0119/TQsLWZnoO4KEwGICm6924wfkua+E49PSKLg///zzxN/mbQa2/sH+8PQ0/Fl/4hp/Htd9/vnn6fr16+nvv/9enTv+BcGpJyxktbgH2AgBEwS2SWl8Bdz2ofv4CrjtdW4QzPA3fMPr20svvbTzw/j1z80uX758/Fq5eeb6K+Bdd921+kxreH0d/oZx+GrDCWEhKxP9RpAQmEVg80PvUTLjd7GWfq1h/K7V8KR03333HX+G9dBDD534IH9cN7x2jl9zGL8eMSSy/lWJdZkOX2sYZDjIdPye1rGwLly4kA4ODtL+/v7xF7hmUWExBCCglsD6F0eHIDe/HDr3i6OjhIavPoyvdut/Szjcsf7F0fUP3YffnfVl1M0vjr7//vvpjz/+WLnpxo0b6dzh4eHR8L6IrNT2G4FBIDSB8e3v4sWL6dyVK1eOhn84f/58aCgkDwEI6CVw8+bN1Qfx/wPviqgmNjzArwAAAABJRU5ErkJggg==">
<h2>Preview</h2>
<img id="preview" src="#">
</body>
</html>
I am trying to run this code but on click nothing happens.
I think the main problem is the image loading, because when I try
to draw the image that is loaded from an tag it works.
<html>
<body>
<canvas id="myCanvas" width="445" height="312"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
<script>
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = "~/Images/my-meme.jpg";
ctx.drawImage(img, 0, 0, img.width, img.height);
}
</script>
</body>
</html>
You'll need to wait for the image to load before using it. For example,
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
// execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path
See https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
Can I use a BPG image as a <div> or <body> background? background: url('bg.bpg'); doesn't work.
There is a Javascript decoder which allows .bpg images to be displayed in <img> tags, but I want to use one as a <body> background.
The Javascript BPG decoder works by converting the source .bpg file into an ImageData object, which can then be drawn to a canvas. So all you need to do is get the canvas as a PNG data string and set that as the body background image:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BPG background example.</title>
<!-- Decoder script from http://bellard.org/bpg/ -->
<script src="bpgdec8a.js"></script>
<script>
"use strict";
function setBackground(filename)
{
// Create a hidden canvas with the same dimensions as the image.
var canvas = document.createElement("canvas");
canvas.style.visibility = "hidden";
canvas.width = 512;
canvas.height = 512;
document.body.appendChild(canvas);
// Create a drawing context and a BPG decoder.
var ctx = canvas.getContext("2d");
var img = new BPGDecoder(ctx);
// Attempt to load the image.
img.onload = function()
{
// Once the image is ready, draw it to the canvas...
ctx.putImageData(this.imageData, 0, 0);
// ...and copy the canvas to the body background.
document.body.style.background = "url('" + canvas.toDataURL("image/png") + "')";
};
img.load(filename);
}
</script>
</head>
<body onload="setBackground('lena512color.bpg');">
<p>Hello, World!</p>
</body>
</html>
I've been trying to find a method to save the canvas to file. My image is too large to use dataToUrl, so I have been trying various toblob methods. It seems that when a patterned fill is used, toblob does not work. Would anyone be able to to me if it is possible for this to work or if there is another way to accomplish this? Thanks
jfiddle example
<!DOCTYPE html>
<html>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>
<script src="jquery.min.js"></script>
<script src="canvas-to-blob.js"/></script>
<script src="FileSaver.js-master\FileSaver.js"></script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var img = new Image();
img.src = "http://www.w3schools.com/tags/img_lamp.jpg";
var pat = ctx.createPattern(img, "repeat");
ctx.rect(0, 0, 150, 100);
//Works with color, but not with pattern
ctx.fillStyle = pat;
//ctx.fillStyle = 'blue';
ctx.fill();
try {
var isFileSaverSupported = !! new Blob();
} catch (e) {
alert(e);
}
alert("toBlob");
c.toBlob(function (blob) {
alert("success");
saveAs(blob, "TruVue.png");
});
</script>
</html>
The reason is due to CORS, images from other domains are restricted - you can show them on the canvas but you cannot extract their bitmap.
As toBlob is a bitmap extracting method like toDataURL or getImageData you won't be able to use these images.
There are a couple of work-arounds:
Upload the image to your own server and load it from there (same domain as you use for the page).
Modify the other server to include Access-Control-Allow-Origin headers (in this case it will probably not be do-able).
Use your own server as an image proxy
BTW: You should also use the image's onload event to be sure the image gets proper loaded before using the image:
var img = new Image();
img.onload = drawFunction;
img.src = "http://www.w3schools.com/tags/img_lamp.jpg";
function drawFunction() {
/// draw here
}
I have a little canvas where random rectangles are drawn every time you click on it. On every new rectangle added, the whole canvas is saved to localStorage.
When the webpage is refreshed the last saved image from localStorage is loaded.
PROBLEM:
I have to refresh twice to get the last image/capture. Rrefreshing once gives me only a blank canvas. Why is this?
Index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./script.js"></script>
</head>
<body>
<canvas onclick="draw(this, event);" id="drawarea" height="240" width="320" style="border:1px solid black;">
</canvas>
</body>
</html>
script.js:
"use strict;"
window.onload=function(){
c=document.getElementById("drawarea");
if (c) initCanvas(c);
};
function initCanvas(canvas){
// Load last canvas
loadLastCanvas(canvas);
}
function draw(canvas, event){
// Draw at random place
ctx=c.getContext("2d");
ctx.fillStyle="#ff0000";
ctx.beginPath();
ctx.fillRect (250*Math.random()+1, 220*Math.random()+1, 40, 30);
ctx.closePath();
ctx.fill();
// Save canvas
saveCanvas(canvas);
}
function saveCanvas(c){
localStorage['lastImgURI']=c.toDataURL("image/png");
}
function loadLastCanvas(c){
if (!localStorage['lastImgURI']) return;
img = new Image();
img.src= localStorage['lastImgURI'];
ctx=c.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
}
The problem is that img.src = "" is an asynchronous call. So you have to add a callback to the onload event. See html5canvastutorials.com for more information.
function loadLastCanvas(c){
if (!localStorage['lastImgURI']) return;
img = new Image();
img.onload = function() {
ctx=c.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
};
img.src= localStorage['lastImgURI'];
}