I have a canvas element in HTML file which i am calling in an <iframe>. The problem is canvas loads some images while ignores others. Even some time the same image doesn't get drawn. I have tried multiple solutions. Path is of local filesystem. The image gets downloaded to the server first and then the script is called. Following is my JS script:
function loadCanvas(e) {
alert(e.getSource().getProperty("sourcePath"));
var path = e.getSource().getProperty("sourcePath");
var source = e.getSource();
alert('source' + source);
var ADFiframe = source.findComponent("if1");
alert('ADFiframe' + ADFiframe);
var iframe = document.getElementById(ADFiframe.getClientId()).firstChild;
alert('iframe' + iframe);
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
alert('innerDoc' + innerDoc);
var canvas = innerDoc.getElementById("imageView");
alert('canvas' + canvas);
var context = canvas.getContext('2d');
var img = new Image();
img.src = path;
alert('path' +path);
img.onload = function() {
alert('img.src' + img.src);
alert('Press OK to load your image');
context.drawImage(img, 0, 0, 700, 700);
};
// img.onerror= function(){
// alert('Ooops,Error loading this image');
// };
}
Related
This question already has answers here:
Callback/scope understanding
(3 answers)
Closed 1 year ago.
I am having trouble drawing an image with CSS filters onto a canvas. I want to apply the CSS filters with sliders/range inputs that I have. The image that the filters will be applied to is an image that you upload from your files. This image is put into a variable in a function I have that will upload the image. The function for the slider is separate, and therefore I can't apply the filters and draw the image again in the function that is activated when the sliders are being dragged.
I need it to be drawn instead of just putting the filters on the canvas itself so that I can download the image with filters.
Here is the javascript code:
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() {
var ratio = this.height / this.width;
canvas.height = canvas.width * ratio;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var container = document.getElementById("container")
var download = document.getElementById("download")
var adjustments = document.getElementById("adjustments")
download.addEventListener("click", function() {
var link = document.createElement('a');
link.download = 'filename.png';
link.href = canvas.toDataURL();
link.click();
});
var prop1 = document.getElementById("prop1");
var open = true;
adjustments.addEventListener("click", function() {
if (open === true) {
prop1.style = "margin-left: -240px;";
adjustments.classList.remove("line");
open = false;
} else if (open === false) {
prop1.style = "margin-left: 50px;";
adjustments.classList.add("line");
open = true;
}
});
var contrast = document.getElementById("contrast");
var brightness = document.getElementById("brightness");
var slider1 = contrast.value;
var slider2 = brightness.value;
function effect() {
slider1 = contrast.value;
slider2 = brightness.value;
ctx.filter = "contrast(" + slider1 + ") brightness(" + slider2 + ")";
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
contrast.oninput = function() {
effect()
};
brightness.oninput = function() {
effect()
};
You could try clearing the canvas with ctx.clearRect() then redraw everything on the canvas. I'd also recommend creating a function to redraw the items just for easier reading.
I want to fill my canvas with a image (base64-string) and than add a text into the canvas.
Initial idea (javascript browser application): I want to set the base64-string txtb64 (Image) as background image of the canvas and than add the text over it.
downloadtext: function() {
var sign = this.getView().byId("SigId");
var txtb64 = signpad.getSignAsJpeg();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = txtb64;
image.addEventListener("load", function(event) {
console.log("Ready!");
});
ctx.drawImage(image, 0, 0);
ctx.fillText('My random text', 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
var image = new Image();
var element = document.createElement('a');
image.src = dataURL;
element.setAttribute('href', image.src);
element.setAttribute('download', 'image');
element.style.display = 'none';
element.click();
},
The problem is I always get a black rectangle as output.
What is wrong with my code, because i can see no error.
It looks like you should put the code needed to download the new image inside the "load" event handler of the image you create. This is needed because the load event could trigger after the code beneath it runs, resulting in an empty image being put onto the canvas.
Also you declare var image = new Image(); twice, which could also be causing issues. Calling one image1 and the other image2 will prevent that.
WARNING Running this snippet triggers a download request.
var data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAFpUlEQVR4nO3a0W7bOBRAQf//T3efFnAFibzeNN2ecgYIEiu2E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CO/f7z6zmjV9smHPeVwRjO32m6ZLw9W5V/tg4IpgZDfr2e1nrT6z+jy8c0WwNd23muxf7WZc030vzuSKYGn62MLq83evd48/2MfijquBpadwTPeqdpHbzb4sD3nnKmBrt7yb/H4XnMkmvWjhCmBkNfv59/Xq+PVzT8tMsyxWXAH8MpN9rukdw9VrzuUq4JdaLe0m0RErVlwJQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQMY/DfmID5+2XZIAAAAASUVORK5CYII=";
var can = document.getElementById('can');
var ctx = can.getContext('2d');
var img = new Image();
img.src = data;
img.addEventListener('load', e =>
{
ctx.drawImage(img, 0, 0);
ctx.fillText('My random text', 100, 100);
var dataURL = can.toDataURL("image/jpeg");
var image = new Image();
var element = document.createElement('a');
image.src = dataURL;
element.setAttribute('href', image.src);
element.setAttribute('download', 'image');
document.body.appendChild(element);
element.click();
});
<canvas width="300" height="300" id="can"></canvas>
I've made a Chrome Extension that:
Takes a screenshot of a website, opens anew window, cuts the image using canvas, and downloads the image. Now I want to display the image so I create an image and set its path to file:///C:/Users/myuser/Downloads/myfile.png.
But the image doesn't show up. I tried removing the "file" or setting a timeout but nothing works, however when I click the image link in the dev console it takes me to the picture and it works.
Here's the code from ´background.js´:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.captureVisibleTab(null, {}, function(image){
var x = window.open();
var cv = x.document.createElement('canvas');
x.document.body.appendChild(cv);
var canvas = x.document.querySelector('canvas');
canvas.width = 928
canvas.height = 490;
var img = new Image();
var code = new Date().getTime();
img.onload = function(){
ctx.drawImage(this, 315, 138, 928, 490, 0, 0, 928, 490);
var toCopy = canvas.toDataURL("image/png");
var link = x.document.createElement('a');
link.download = code + '.png';
link.href = toCopy;
link.click();
setTimeout(function(){
var el = new Image();
el.src = 'file:///C:/Users/myuser/Downloads/'+code+'.png';
x.document.body.appendChild(el);
x.console.log(x.location);
}, 2000);
canvas.parentElement.removeChild(canvas);
}
img.src = image;
var ctx = canvas.getContext('2d');
});
});
I develop Photoshop extension that sends images to the server.
Edit: Extensions in photoshop build from html file that define the GUI, js file that basically is the same as any js file, but it's can also launch photoshop function and it is execute from photoshop.
I need to send the images from the file system of the user (from C:\path\to\images)
To encode the images I converted them to dataURL (base64).
The problem occurs in the first time that I convert the images to dataURL. But in the second time and so, it manages to convert the images and everything is fine. In the first time the image doesn't loaded.
I have a folder where the images are and I want to upload the pictures from there, I used a loop that runs on photos and set them into <img src=path> to and then it converts them based 64 via <canvas>.
My code:
function convertLayersToBase64(imgHeight, imgWidth){
var img = new Image();
images = [];
for (var i=0; i<=imagesLength; i++){
path = folder + "layer " + i +".png";
img.src = path;
var canvas = document.createElement("canvas");
canvas.height = imgHeight;
canvas.width = imgWidth;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
images.push( dataURL );
}
return images;
}
I tried to delay the conversion by delay:
function delay(time) {
var d1 = new Date();
var d2 = new Date();
while (d2.valueOf() < d1.valueOf() + time) {
d2 = new Date();
}
}
JQuery when ready:
$(function(){
images.push(getBase64Image());
});
Img.complete
while(!img.complete)
continue;
(In the last example the code stuck in loop)
To put the function in:
img.onload = function(){
//the function here..
//when I use this method it succeed to convert
//only the last image.
}
Nothing worked..
I tried everything, please tell me what to change and how to fix that.
Edit: It's seem to me that the only way to load an image it's when the code
The function onload is an asynchronous action. You cannot just return images as the last statement within your convertLayersToBase64 function. You should either use promises, or a more simple approach would be to use a callback function.
function convertLayersToBase64(imgHeight, imgWidth, callback){
var images = [];
for (var i = 0; i <= imagesLength; i++) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.height = imgHeight;
canvas.width = imgWidth;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL();
images.push(dataURL);
if(images.length === imagesLength) {
callback(images);
}
}
path = folder + "layer " + i +".png";
img.src = path;
}
}
You would call this like:
convertLayersToBase64(200, 200, function(images) {
console.log('hii, i got images', images);
});
This is obviously without any form of error check, or even best practice guidelines, but I'll leave it up to you to implement that.
I'm attempting to pull an image (in this case, /camera/frame, which is a known-good JPG), and load it as the background of my document.body.
Here's my code thus far:
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
console.log("onload");
document.body.style.backgroundImage = this.src;
};
backgroundImage.src = 'camera/frame';
"onload" prints as expected, and this.src prints out the full URL to /camera/frame, however document.body.style.backgroundImage remains "".
I believe you may be missing two things.
var path = 'path/to/image.jpg';
document.body.style.background='url('+path+')';
Canvas 2D to the rescue!
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(this, 0, 0, this.width, this.height);
};
backgroundImage.src = 'camera/frame';
backgroundImage.width = $(window).width();
backgroundImage.height = $(window).height();
Loads the image in the background, then draws it into the canvas seamlessly!