canvas.toblob fails when a patterned fill is used - javascript

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
}

Related

How do I load the image from file chooser and get it to load on the canvas so that i can edit it using Javascript?

I have been using a pixel editor called pixel paint and I wanted to create a button that allows me to load any image onto the canvas. Currently, I have been researching and testing multiple methods online and I am still struggling to get the image loaded in. Here is the code for the script.js method.
function showSelectedFile(){
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
var file = document.getElementById("inputfile");
var name = file.value.replaceAll("\\","").replace("C:fakepath","").replace(".png","");
document.getElementById("myText").value = name;
window.URL = window.URL || window.webkitURL;
img.onload = function()
{
context.drawImage(img,0,0)
}
img.src = "/Users/angadp/Dropbox/Mac/Downloads/pixel-paint-master/" + name + ".png";
}
Also, in the script.js file I have tried to use
var canvas = document.getElementById("canvas-div")
but it gets the following error
Uncaught TypeError: canvas.getContext is not a function
In the index.html file the code is currently using <div id="canvas-div"></div>. So I am not really sure how to load the image onto the canvas that is using the div tag. Also at the beginning of the html file I am using <input id='inputfile' type='file' accept = ".png" name='inputfile' onChange='showSelectedFile()'> which makes the choose file button.
I also have a picture of pixel paint so that you would know what I am talking about.
Can you please provide me with some help on how to solve all these solutions. Thank you. I have also attached the hyperlink to the original pixel-paint so that you can download and test it.
Pixel Editor Menu for you to download and test
You can load image on change of file. Then createObjectURL (that's data:something;base64). Then load it on an image finally draw it on the <canvas>.
function loadFile(event) {
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext('2d');
var dummy = document.getElementById('dummy');
dummy.src = URL.createObjectURL(event.target.files[0]);
dummy.onload = function() {
ctx.drawImage(dummy, 0, 0, 600, 300);
// Set line width
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();
// free memory
URL.revokeObjectURL(dummy.src)
dummy.parentNode.removeChild(dummy)
}
};
canvas {
width: 600px;
height: 300px;
}
<input type="file" accept="image/*" onchange="loadFile(event)">
<canvas></canvas>
<img id="dummy" />

Creating image from two other images using javascript [duplicate]

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

getting html canvas image as javascript object

I want to get html canvas image as javascript object. I looked samples from internet. But all samples are getting images from a source to canvas like this:
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
</body>
But my problem: There is an image on canvas element that created by pencil. I want to get that image as object and post to server. But I could not get.
have you tried canvas.toDataURL()?
more hardcore way might be canvas.getContext('2d').getImageData() would return ImageData object.

canvas to image shows as no image (blank)

I'm working on converting a canvas to an image using dataurl. I have the following code that outputs no error in console. Seems to work somewhat, but when i access the dataurl it shows a blank image.
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
var myImage = context.drawImage(imageObj, 0, 0);
var myImg = canvas.toDataURL("image/png");
document.getElementById("canvasimg").setAttribute("src", myImg);
};
imageObj.src = "http://img801.imageshack.us/img801/5641/3cc67ca1a74049ce99bc92b.png";
};
<canvas id="myCanvas" width="578" height="400"></canvas>
<img id="canvasimg" alt="" src="">
Look at what you are doing. You are drawing the image when the image loads, but you are converting it to a data url before the image has been drawn! Move that toDataURL call and the setAttribute call INSIDE the onload function.
Testing the code you have posted, I get a Security Error raised. Which is to be expected. The canvas has a clean-origin flag, and once that flag is false, you can't pull data out of it.
Here's a more detailed, related question
Documentation linked to in the answer

Can you combine multiple images into a single one using JavaScript?

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

Categories