My requirement is to return data URL. But, when I run the application, there is an run-time error:
JavaScript runtime error: Unspecified error.
Here is the code that I have used. Temp path is the path where is location of image is.
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = "#tempPath";
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);'
Try following code, It worked for me:
<body>
<canvas id="myCanvas"></canvas>
<img id="profileImg" alt=""/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawImg();
});
function drawImg() {
try {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = $('#profileImg');
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
} catch (e) {
if (e.name == "NS_ERROR_NOT_AVAILABLE") {
// This is a bug in Firefox. The easiest fix is to simply keep trying until the error goes away,
//since no event fires at the correct time.
// Wait before trying again; you can change the length of this delay.
setTimeout(drawImg, 100);
} else {
throw e;
}
}
}
</script>
</body>
Works well with IE as well. Hope this helps.
Related
I want to create a Whiteboard application on which the User can draw (I'm using an HTML <canvas>). I just completed coding a function that imports an PNG image and draws it onto the Canvas:
var canvas = document.getElementById('can');
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
function drawImageOntoCanvas (e) {
var input = e.target;
var img = new Image();
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
img.src = dataURL;
ctx.drawImage(img, 10, 10);
};
reader.readAsDataURL(input.files[0]);
}
<input id="uploadFromPC" type="file" accept='image/png' onchange="drawImageOntoCanvas(event);"></input>
<canvas id="can" width="1000px" height="500px" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>
This works, but only sometimes for some reason. It doesn't work at first, then, when I reload the page, it works again. Then, it doesn't work, but it does after reloading and so on.
I tried logging the Data URL in the console, as well as the result of the reader. Both work perfectly fine.
Is there something I'm doing wrong here? I'm not very familiar with JS, so it could be that I'm missing something here.
Thanks in advance
The problem is that, depending on timing, you might be drawing the image before it has finished loading.
You can address that as follows, even though I would suggest using a little more modern JavaScript (addEventListener(), const, let, promises, etc.):
var canvas = document.getElementById('can');
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
function drawImageOntoCanvas(e) {
var input = e.target;
var img = new Image();
var reader = new FileReader();
reader.onload = function() {
img.src = reader.result;
img.onload = function() {
ctx.drawImage(img, 10, 10);
}
};
reader.readAsDataURL(input.files[0]);
}
<input id="uploadFromPC" type="file" accept='image/png' onchange="drawImageOntoCanvas(event);"></input>
<canvas id="can" width="1000px" height="500px" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>
$("#fileinput").change(function (e) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function () {
ctx.drawImage(img, 0, 0, img.width, img.height,
0, 0, canvas.width, canvas.height);}
});
So far it is working good. Now I'm trying send the image to server as form data via ajax-
var fd = new FormData();
var canvasData = canvas.toDataURL("image/png");
//I tried
var canvasData = canvas.getImageData();
//Gives Uncaught TypeError: canvas.getImageData is not a function(…)
fd.append("InsidePhoto", canvasData);
But it sends nothing. Ajax code has been tested and works fine. I think I can not get the image from canvas. Any idea?
Here's a worked example. Hard to tell quite where your problem lies with the code you've omitted. In the second snippet for instance, we can't tell if canvas is valid.
php code: (postExample.php)
<?php
//postExample.php
printf("<img src='%s'/>", $_POST['InsidePhoto']);
?>
html code
<!doctype html>
<html>
<head>
<script>
"use strict";
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
function ajaxPostFormData(url, formData, onSuccess, onError)
{
var ajax = new XMLHttpRequest();
ajax.onload = function(){onSuccess(this);}
ajax.onerror = function(){onError(this);}
ajax.open("POST",url,true);
ajax.send(formData);
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('imgInput').addEventListener('change', onFileInputChanged, false);
}
function onFileInputChanged(evt)
{
var can = byId('preview'), ctx = can.getContext('2d');
var img = new Image();
img.onload = function()
{
can.width = img.width;
can.height = img.height;
ctx.drawImage(img,0,0);
var fd = new FormData();
var canvasData = can.toDataURL("image/png");
fd.append("InsidePhoto", canvasData);
ajaxPostFormData('postExample.php', fd, onSuccess, onError)
}
var dataSrc = URL.createObjectURL(this.files[0]);
img.src = dataSrc;
function onSuccess(ajax)
{
console.log(ajax.response);
var div = newEl('div');
div.innerHTML = ajax.response;
document.body.appendChild( div.childNodes[0] );
}
function onError(ajax)
{
console.log(ajax.response);
}
}
</script>
<style>
</style>
</head>
<body>
<input type='file' id='imgInput'/>
<canvas id='preview'></canvas>
</body>
</html>
You need to use CanvasRenderingContext2D's getImageData(x, y, width, height) function to get the canvas' image data not the canvas element's.
The first 2 values are the starting positions, set these to 0 to start from the top-left edge.
The second 2 values are the width and height of the area, so set these to canvas.width and canvas.height respectively.
This is my javascript code, but nothing seems wrong too me. My html id is not wrong either. I was following a tutorial on youtube and it worked for the person that did it. Can anyone help me with this?
var canvas;
var ctx;
var background;
var width = 300;
var height = 200;
var cloud;
var cloud_x;
function init() {
canvas = document.getElementById("mycanvas");
width = canvas.width; //THIS IS WHERE I GET MY ERROR
height = canvas.height;
ctx = canvas.getContext("2d");
// init background
background = new Image();
background.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/forest.png';
// init cloud
cloud = new Image();
cloud.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/cloud.png';
cloud.onload = function(){
cloud_x = -cloud.width;
};
return setInterval(main_loop, 10);
}
function update(){
cloud_x += 0.3;
if (cloud_x > width ) {
cloud_x = -cloud.width;
}
}
function draw() {
ctx.drawImage(background,0,0);
ctx.drawImage(cloud, cloud_x, 0);
}
function main_loop() {
draw();
update();
}
init();
My html
<canvas id="mycanvas" width="640" height="480">Alternative text if browser don't support canvas.</canvas>
Change this line:
init();
By this line:
document.addEventListener('DOMContentLoaded', init, false);
The init function will be called when the DOM is ready.
jsfiddle
I'm trying to make a game in JavaScript and i need to get pixeldata from an image. i'm using getImageData().data; and it is working all good on Internet Explorer, but on Chrome i get this error:
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
I've been looking around for solutions but nothing seems to work, anyone have a good idea?
here is my code: `
var
width = 600,
height = 400,
img,
canvas,
ctx;
function main() {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
init();
loop();
}
function init() {
img = new Image();
img.src = "test.png";
}
function update() {
}
function render() {
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(10, 10, 1, 1).data;
console.log(data);
}
function loop() {
window.requestAnimationFrame(loop);
update();
render();
}
main();`
The file is running localy and not on a server.
If you load your page or file using file://... it will trigger CORS issues as well.
When testing locally, always use a local server so you can load the files from localhost.
Also a side issue: remember to use the onload handler for the image:
function init() {
img = new Image();
img.onload = ... // don't start loop without it...
img.src = "test.png";
}
Try it:
function init() {
img = new Image();
img.crossOrigin = "Anonymous";
img.src = "test.png";
}
I'm experimenting with the canvas element, but for some reason it doesn't display my image.
I use the following code:
function Canvas() {
this.field = function() {
var battlefield = document.getElementById('battlefield');
var canvas = battlefield.getElementsByTagName('canvas')[0];
return canvas.getContext('2d');
}
}
function Draw(canvas) {
if (!canvas) {
alert('There is no canvas available (yet)!');
return false;
}
this.canvas = canvas;
this.grass = function(pos_x, pos_y) {
var terrain = new Terrain();
var specs = terrain.grass();
var img = new Image();
img.onload = function(){
canvas.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
console.log('success???'); // this is being output
};
img.src = '/img/terrain.png';
}
}
(function() {
var canvas = new Canvas();
var draw = new Draw(canvas.field());
draw.grass();
})();
There are no errors, but the image just doesn't display. I've verified if the image exists and it does. I also verified the specs and they do contain what they should:
dimension_x: 25
dimension_y: 25
position_x: 0
position_y: 0
Any idea what I'm doing wrong?
http://jsfiddle.net/uwkfD/3/
pos_x and pos_y are undefined in your code. It works if you pass values for them to draw.grass():
draw.grass(0, 0);
DEMO
Tested in Chrome and Firefox.
This may be because you need a context to draw on.
Try:
this.context = canvas.getContext('2d')
Then call your draw functions on the context object not the canvas object:
this.context.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
It also appears that your reference to canvas is wrong too, it should be this.canvas (or this.context) not just canvas, at least as I understand scope in javascript.