i am using following code to draw canvas and save it as png image using toDataUrl.
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
window.onload = function(images) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sources = {
darthVader: "http://a1.sphotos.ak.fbcdn.net/hphotos-ak-snc6/228564_449431448422343_1996991887_n.jpg",
yoda: "http://a4.sphotos.ak.fbcdn.net/hphotos-ak-snc7/427489_449423165089838_503188418_n.jpg"
};
loadImages(sources, function(images) {
context.drawImage(images.darthVader, 250, 30, 250, 250);
context.drawImage(images.yoda, 530, 30, 250, 250);
});
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById("canvasImg").src = dataURL;
};
</script>
</head>
<body>
<canvas id="myCanvas" width="850" height="315"></canvas>
<img id="canvasImg" alt="Right click to save me!">
</body>
</html>
But my png image is shown as blank image. i see only a blank white image.
i searched for this but found nothing on this.
i am using php and chrome browser.
what is wrong here?
You are first calling loadImages, then getting the data URL right after that loadImages call. However, as your loadImages implementation shows, calling it merely starts the loading process; the callback is called when all images have been loaded, which is some time in the future.
Currently you're getting a blank image because the images have not been loaded yet, so your callback is not called yet, and as a result your canvas is still empty.
In short, everything that relies on the images having being loaded (e.g. your expected toDataURL result) should be executed when those images are actually loaded - thus in the callback.
loadImages(sources, function(images) {
context.drawImage(images.darthVader, 250, 30, 250, 250);
context.drawImage(images.yoda, 530, 30, 250, 250);
var dataURL = canvas.toDataURL();
document.getElementById("canvasImg").src = dataURL;
});
Related
This is my first time using HTML canvas. I have been given a working camera that returns images as a base64 string. I am trying to pass this string to a new function that handles the image resizing(the actual dimensions aren't important right now as I am just testing the resizing).
Right now I am getting a blank image from my generateThumbnail function. Below I have attached an image of the output in the application, as well as an image of the console output.
For the first attached image, you will see 2 photos. The photo on the left is the original which is working correctly (it is all black because my webcam is covered). The photo on the right is the blank output when I attempt to resize.
generateThumbnail(imageData) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 300);
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
image of taken photos
image of console output from thumbnail base64
Although your code is not working on the embedded fiddle, I think your problem is because the image has not loaded yet as you're returning dataUrl as soon as you execute your method.
dataUrl
should be returning inside img.onload method , maybe something like this will work?
** EDIT **
Make sure you set width and height of your canvas as well.
const generateThumbnail = (imageData) => {
let canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
document.querySelector(".canvas").appendChild(canvas);
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0 , 0, 300, 300);
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
document.querySelector(".image").appendChild(img);
}
window.onload = () => {
generateThumbnail(window.image_base64);
}
.canvas, .image {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 300px;
color: white;
}
.image { border: solid 1px white; }
.canvas {
left: 310px;
top: 0;
width: 300px;
height: 300px;
}
body {
background: purple;
}
<div class="image"></div>
<div class="canvas"></div>
<script>
window.image_base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAMAAABOo35HAAAFU2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QI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AEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRCEn4D/BXJsajf86qhZAAAAAElFTkSuQmCC";
</script>
Requirement:
Users can type in text that goes as an overlay on top of an image.
Users can download the image with the overlay.
To do this, I'm drawing the image onto the canvas, filling with the text and then setting the link's href to the canvas's dataURL.
Findings:
I can see the text overlay on the image in the canvas just fine.
If I right-click on the canvas and download the image, I can see the text overlay just fine.
If I click on the link, I see the original image without the text overlay.
What did I miss?
Here's the snippet:
var imgURL = 'https://upload.wikimedia.org/wikipedia/commons/5/56/Neptune_Full.jpg';
function loadCanvas(dataURL) {
var canGreeting = document.getElementById('canGreeting');
var context = canGreeting.getContext('2d');
// load image from data url
var imageObj = new Image();
imageObj.crossOrigin = 'anonymous';
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.font = "20px sans-serif";
context.fillStyle = "#FFFFFF";
var arrayOfLines = $('#txtGreetingText').val().split('\n');
var y = 50;
var i = 0;
$(arrayOfLines).each(function() {
context.fillText(arrayOfLines[i], 50, y);
i++;
y += 30;
});
};
imageObj.src = dataURL;
lnkDownload.download = "card.jpg";
lnkDownload.href = imageObj.src;
}
$(document).ready(function() {
loadCanvas(imgURL);
$("#txtGreetingText").on("keydown", function(e) {
loadCanvas(imgURL);
});
});
textarea {
width: 420px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea name="txtGreetingText" id="txtGreetingText"></textarea>
<br/>
<canvas id="canGreeting" width="480" height="480"></canvas>
<br/>
<a id="lnkDownload">Download this card</a>
href attribute should be pointing to base64 encoded image of the canvas source. Do this:
$(arrayOfLines).each(function() {
context.fillText(arrayOfLines[i], 50, y);
i++;
y += 30;
});
// udpate link to image
// Grab base64 encoded URL
var url = canGreeting.toDataURL("image/png;base64;");
lnkDownload.href = url;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>
</body>
</html>
I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?
EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".
original code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
init();
editted code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.
<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.
Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.
And this snippet:
var canvas = document.getElementById("painting"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
ctx.drawImage(image, 30, 50);
};
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
If the image you want to draw is not in the DOM already you can load an image directly from a URL with a few lines of javascript.
function loadAndDrawImage(url)
{
// Create an image object. This is not attached to the DOM and is not part of the page.
var image = new Image();
// When the image has loaded, draw it to the canvas
image.onload = function()
{
// draw image...
}
// Now set the source of the image that we want to load
image.src = url;
}
loadAndDrawImage("http://www---.png");
I'm learning HTML5 and Javascript and I'm trying to draw an image on a canvas. I have the following code which draws the image if I step through the code after breaking on the line marked below. If I don't debug then the image is not drawn at all. What am I doing wrong? Firefox 10 with FireBug 1.9.
Note that although there's a loop to handle multiple images, I've only been selecting one. I figure if one doesn't work, a hundred won't work either. ;-)
<!DOCTYPE html>
<html>
<body>
<input type="file" id="files" name="files[]" multiple />
<canvas id="picCanvas" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render images
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
var img = document.createElement('img'); // <-- BREAK HERE!
img.src = e.target.result;
var canvas = document.getElementById('picCanvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
You have to wait until the image element is fully loaded by the browser before calling the drawImage method, even if your image element is created from a base64 string and not from an external file. So just make use of the onload event of the image object. A quick fix would be like this:
var img = document.createElement('img');
img.onload = function()
{
var canvas = document.getElementById('picCanvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
}
img.src = e.target.result;
I have JavaScript code.
<canvas id="view" width="120" height="120">
błąd
</canvas>
<script>
var _view = document.getElementById("view");
if(_view.getContext) {
var canvas = _view.getContext("2d");
var img = new Image();
img.src = "fajnetlo.png";
canvas.drawImage(img, 0, 0, 50, 50, 0, 0, 50, 50);
}
</script>
In the canvas image isn't displayable. Image and file is in one directory. Web browser rectangle etc. drawing, or image not. Why?
Do the drawImage in the onLoad callback of the image. MDN quote:
When this script gets executed, the
image starts loading. Trying to call
drawImage before the image has
finished loading will throw in gecko
1.9.2 and earlier, and silently do nothing in Gecko 2.0 and later. So
you must use an onload event handler:
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here
};
img.src = 'myImage.png'; // Set source path
Source: https://developer.mozilla.org/en/Canvas_tutorial/Using_images
<canvas id="view" width="120" height="120">
błąd
</canvas>
<script>
var view = document.getElementById("view");
var ctx= view.getContext("2d");
img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 50, 50, 0, 0, 50, 50);
}
img.src = 'fajnetlo.png';
</script>