Copy multiple HTML5 layered canvases to one image in JavaScript - javascript

I have multiple HTML5 canvases which are placed on top of one another. The order is important. Canvas 2 will be placed on Canvas 1 and so forth.
a) Is there a way I can create a single image (using toDataURL()) of all of these canvases keeping the same order?
b) And, then how can I copy this image to a clipboard so that it can be pasted in other applications?

Steps:
Create a new Canvas (maybe hidden)
Copy both canvas to the new canvas
Copy to image using canvas.toDataURL()
See this fiddle: http://jsfiddle.net/137f623c/
Let's say you have 3 canvas (2 source and 1 combined - hide this if you want) and an image:
<canvas id="myCanvas1" width="200" height="200"></canvas>
<canvas id="myCanvas2" width="400" height="200"></canvas>
<canvas id="combined" width="400" height="200"></canvas>
<img src="" id="image" />
And, the Script:
var canvas1 = document.getElementById("myCanvas1");
var ctx1 = canvas1.getContext("2d");
ctx1.fillStyle = "red";
ctx1.fillRect(10,10,100,100);
var canvas2 = document.getElementById("myCanvas2");
var ctx2 = canvas2.getContext("2d");
ctx2.fillStyle = "blue";
ctx2.fillRect(50,50,300,100);
var combined = document.getElementById("combined");
var ctx = combined.getContext("2d");
ctx.drawImage(canvas1, 0, 0); //Copying Canvas1
ctx.drawImage(canvas2, 0, 0); //Copying Canvas2
document.getElementById("image").src = combined.toDataURL()
Don't forget consider MarkE's Answer (for part b) and also see for compatibility among browsers. As far for copying I see that most modern browsers have Copy Image when right clicked. For old browsers, :\ uploading to server and downloading might be the solution.

As to part b) of your question...
You will have problems copying the merged canvas content to the clipboard because the required Clipboard API is not yet uniformly or well supported by modern browsers:
http://caniuse.com/#feat=clipboard
A workaround would be to:
Upload the canvas.toDataURL to your server and save it as an image file,
Download that image from the server and add it as an img element.
Then users can right-click-copy the img to their clipboard.

Related

How to get a high quality canvas to PNG conversion

I have a requirement to take the canvas from a webpage and convert it to PDF in the backend so it can be saved on the server and downloaded & printed at a later time at 600 DPI.
I have followed this question, and I have a working prototype of the code: AJAX call to send the canvas to backend in Base64 and then a Java function to convert it to PDF.
However, the problem is that the quality of the image is dependent on the screen/browser window size the user has when he clicks the button to trigger the image creation - a fullscreen browser will create a higher-res image than a partial window browser. Example: Both taken on my PC but on the latter the window is about half the screen size.
I was thinking of somehow creating the canvas on a headless browser with preset size, and that would at least make the quality consistent across users, but I have no idea how to dynamically change the image so I can keep it at 600 DPI no matter the paper size the user chooses to use.
Do I have to draw the canvas shapes directly onto PDF? I know that would fulfill the DPI requirement, but is that even possible to do from an AngularJS/Java stack?
You can decide the proper size for the canvas and then modify the way it's displayed via CSS. Here, the final size is set as 2000x2000 and it will be saved as such (by clicking on it), regardless of the viewport size:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Draw the ellipse
ctx.beginPath();
ctx.lineWidth = 10;
ctx.ellipse(1000, 1000, 500, 800, Math.PI / 4, 0, 2 * Math.PI);
ctx.stroke();
// Draw the ellipse's line of reflection
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(0, 2000);
ctx.lineTo(2000, 0);
ctx.stroke();
canvas.addEventListener('click', function (e) {
var dataURL = canvas.toDataURL('image/png');
var link = document.createElement("a");
link.download = "finalsize.png";
link.href = dataURL;
link.click();
});
<body style="display:flexbox">
<canvas id="canvas" width="2000" height="2000" style="width:100%; "></canvas>
</body>

How can I restore a saved image of a canvas drawing into a new canvas instance?

I am using sketch.js http://intridea.github.io/sketch.js/ so users can create drawing in my app. Once they are finished drawing, and click save, I convert the drawing into a png image using this function:
convertCanvasToImage = (canvas) ->
image = new Image()
image.src = canvas.toDataURL("image/png")
image
And then I just append the image to the DOM.
But what if a user wants to edit the drawing afterwards? How can I take that image and add it to the canvas that sketch.js uses?
I tried the following with failed results. When you click the png image I run this code to try to append the image to canvas, but it does not seem to work at all. The canvas is in a modal and once it appears I run the following code to append the image to canvas, but no image appears.
template.$('#sketchModal').on 'shown.bs.modal', (e) ->
c = document.getElementById("sketchPad")
ctx = c.getContext("2d")
ctx.drawImage(e.target, 0, 0)
I haven't used sketch js before, but seeing this code I came with an idea
<div class="tools">
Marker
Eraser
</div>
<canvas id="tools_sketch" width="800" height="300" style="background: url(http://farm1.static.flickr.com/91/239595759_3c3626b24a_b.jpg) no-repeat center center;"></canvas>
<script type="text/javascript">
$(function() {
$('#tools_sketch').sketch({defaultColor: "#ff0"});
});
</script>
You don't want to append the image in canvas but rather add it as a background.
Try it and please inform me if it worked.

How to make a copy of image without src?

I have to make a copy of given image after it's loaded. The problem is that the image is not usin static url and the image is different each time, it's generated with php on the server side. The link keeps the same every time. What I have to do is to make a copy of this already loaded image. How can I do that using HTML5 and canvas, or is there any other way to do that? I know that it can be done with canvas, but I need the src of the image. The problem is that it's not a static url, and when I do it, I get another picture instead of the loaded one. Any ideas?
You can use a canvas; it's pretty simple:
<img src=http://placekitten.com/300/340 id=kitteh>
<canvas id=c></canvas>
JS:
var canvas = document.getElementById("c"),
kitteh = document.getElementById('kitteh'),
ctx = canvas.getContext('2d');
canvas.height = kitteh.height; canvas.width = kitteh.width;
ctx.drawImage(kitteh, 0, 0);

How to display an image if browser doesn't support HTML 5 Canvas

I have some HTML 5 content with Javascript which generates a set of rectangles and texts with links.
That code doesn't work on the IE8 because it doesn't support HTML 5.
I want the browser to display an image instead of a text, if the page is shown in an IE8 or any other browser that doesn't support HTML5.
I tried this code but it didn't gave me the expected output.
function draw(){
canvas = document.getElementById("myCanvas");
// check if supported
if(canvas.getContext){
ctx=canvas.getContext("2d");
var ctz=canvas.getContext("2d");
ctz.fillStyle="#FF0000";
ctz.fillRect(0,0,150,75);
//..Rest of the code to add html5 content
}else{
var img = document.createElement("img");
img.src = 'http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg';
img.width = 276;
img.height = 110;
img.alt = '';
document.body.appendChild(img);
}
}
draw();
What could be the error here?
By the definition of the canvas element, its content acts as fallback content: it is ignored by browsers that implement the element, but it will naturally be processed and displayed by older browsers that simply ignore the <canvas ...> and </canvas> tags. Example:
<canvas id=myCanvas>
<img src=http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg
alt="" width=276 height=110>
</canvas>

canvas not drawing images

I'm just trying to figure out how to get an image to draw on a canvas. I followed a tutorial on W3 schools, but when i tried it on my own it doesn't seem to be working. I copy and paste the code below into an HTML file, and the image never loads into the canvas. I downloaded the picture into the same directory. I've been asking around, and looked online, but no one seems to know what the problem is.
I'm using an updated version of chrome (Version 29.0.1547.76 m).
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">
<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
this.ctx.drawImage(img,10,10);
</script>
</body>
</html>
Your image probably hasn't finished loading at the point you are using drawImage:
HTML
Add onload handler in img tag:
<img id="scream" onload="draw()" src="...
Then the function to handle it:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
function draw() {
ctx.drawImage(img,10,10);
}
Online demo here
Be aware of that where you place the scripts in your document matters as well.
I would recommend you setting the src attribute in JavaScript as well. That makes it more "safe" to handle the onload (or subscribed event with img.addEventListener('load', ...).
you should use the following approach that first let the image loaded then display:
image.onload = function() {
pic.getContext('2d').drawImage('your image to display', 0,0);
}
"If you try to call drawImage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded."
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
Source

Categories