Create Image from Div - javascript

I'am new to canvas. I was using the following code to insert a image in canvas from another image. When I try to create image from a div using the code
<!DOCTYPE html><html>
<head>
<title>test</title>
<script type="text/javascript">
var colour="#ccc",bgcolour="#fff";
function paint(hhh){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var img=document.getElementById('mine');
ctx.drawImage(img,0,0);
}
</script>
</head>
<body onload="paint('scribble');" >
<canvas id="canvas" style="border:solid 1px;" width="400" height="400">g</canvas> <div id="mine">canvas</div>
</body>
</html>
It is not working.
My question is how to draw a image from div instead of another image?

The only images you may draw with drawImage on a Canvas, are those declared in "src" attributes of a image object. Specifications may be found here.
I don't know any method to put the contents of a div tag inside of an image object and I don't think this is really an easy thing to do. You should think about alternatives...

The problem is you can't draw to the canvas from an element that isn't an image, or another canvas element. Check out this MDN article for some more information Using images with canvas
Another issue is you are treating a div like an image in your events, divs do not have an onload event.

Related

Clipping multiple images in HTML5 canvas

I am working on HTML5 canvas with image manipulation. In my canvas I have number of images. When I want to clip the images individually. But when I clip one image by creating a shape and use clip() function, it is working fine. But the problem arise when I try to clip another image using the same method. As the canvas stored the previous shape it will concatenate with the new one and clip the second image accordingly. I want destroy the previous shape. Please note that I can't use the clearRect() to clear the canvas as my previous clipped image is there.
Please ref the link :
Demo Problem
In the link drag the image into canvas predefined layer and drag the image around. You can clearly see that the image got clipped properly if it try to go out of the border.
Now drag another image into the canvas in a different box. Now you can see the clipping is not functioning properly.
Here what I have done in the script :
JS Script
Here the JSFiddle Link
JSFiddle Link
Can you help me to fix this issue?
It will be helpful if you find another way to clear the previous shape.
Thanks in advance.
I have fix the issue by own. The canvas doesn't provide the multiple image clip option. So if you want to clip multiple image in your canvas you have to use your own clip function. Just clear the area by clearRect() of the canvas outside your selection. Iterate this process for each image and you are done !
Solution Link :
Solution Demo
JS Script Link :
JS Script
Thanks.
The best solution I could find is to use a hidden canvas, and draw to that, then use the putImageData method onto your main canvas.
var c = document.getElementById("myCanvas");
var ctemp = document.getElementById("myCanvasTemp");
var ctx = c.getContext("2d");
var ctxTemp = ctemp.getContext("2d");
ctxTemp.fillStyle = "red";
ctxTemp.fillRect(10, 10, 50, 50);
ctxTemp.fillStyle = "blue";
ctxTemp.fillRect(20, 20, 50, 50);
function copy() {
var imgData = ctxTemp.getImageData(10, 20, 50, 10);
ctx.putImageData(imgData, 10, 10);
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="myCanvasTemp" width="300" height="150" style="display:none;">
Your browser does not support the HTML5 canvas tag.</canvas>
<br /><br />
<br />
<button onclick="copy()">Copy</button>

simple HTML5 canvas image not displaying

I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.
HTML:
<canvas width="840" height="900" id="Canvas6">
Your browser does not support this feature.
</canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>
Main.JS JAVASCRIPT:
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
//Create a variable to hold our image
var srcImg = document.getElementById("img1");
//Draw an image directly onto the canvas
ctx.drawImage(srcImg, 0,0);
//Draw a scaled down image
//drawImage(srcImg, dx, dy, dw, dh)
}
}
In html file, the first best thing you have done is used the 'script' tag right at the end of the html file.
This ensures that the "Critical Render Time" is minimized, and the display items in HTML are shown first. (Not a huge impact on this case, because here you are using the JS to draw/display, but this approach is really good when you use your js for other purposes like calculations etc., and you don't want to stop the other HTML items from displaying because of an ongoing calculation.)
Now that the canvas is ready, its time to throw the image on the canvas.
Try using the border property (style="border: 2px dotted black") to see the container area of the canvas.
Hmmm !! But the image doesn't show in canvas. WHY ??
Images(or any other files) take atleast some time to get processed. By the time they are getting processed to be loaded on the screen, your canvas is already getting displayed. Hence you see an empty canvas.
So, the solution is to make everything else wait, till the time image gets loaded.
How do we do that ? Just use the "Event Listener".
EventListener is the property of Window object. (window.addEventListener("load", some_func_to_run , false);). We generally use this, when we want our window/page/browser to wait for something, but hey , we can use it for our images as well.
var cvs = document.getElementById("canvas"); // Getting the control of the canvas
var ctx = cvs.getContext("2d"); //Getting the control of the useful HTML object getContext . This object brings in a lot of useful methods like drawImage, fillRect etc.
//create images
var bg = new Image(); // Creating image objects
bg.src = "images/bg.png"; //Setting the source file
//create images ends
//load images first
bg.addEventListener("load" , draw , false); //**IMPORTANT : Just remove this line and you will start facing this problem of empty canvas again
//loading images ends
function draw() {
ctx.drawImage(bg,0,0); // Putting the image and its coordinates on the canvas
}
draw(); // Calling the draw function to put the image on canvas
<html>
<body>
<canvas id="canvas" width="288" height="512" style="border: 2px dotted black"> </canvas>
<script src="flappyBird.js"></script>
</body>
</html>
So, it all about using Event Listener and asking everything to wait till the image gets loaded.
Hope this help. :)
If you try to place an image on a Canvas before it has loaded, it will not show. It is not like the img tag that will show the image whenever it loads. I surrounded your JS with an onload and it worked for me.
document.getElementById("img1").onload = function() { /* Your JS */ };
You have to wait for the image to load before you can draw it on the canvas, so set your drawing code to run on the window load event (by which time all images are loaded). Also, you don't need to include the markup for the image on the page, where you have to then prevent it from displaying with CSS. You can just create the image object and set the source attribute in the javascript. For example:
var img = document.createElement('img');
img.src = 'image/logo.png';
window.addEventListener('load', function(){
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.drawImage(img, 0,0);
}
}
});

Resizing image : Function returning a canvas in js

I've read several articles/stackoverflow's questions about resizing images in order to upload them. But I did'nt found a function like this:
function resize(src,maxWidth, max Height){
// some staff, creating a new Canvas and drawing the src inside
return canvas;
}
Until now, I've only seen piece of code like :
var img = new Image();
img.src=src
img.onload(function(){
// Creating a Canvas here and do all the needed operations with the Canvas...
}
In this case, I don't see how to get the created Canvas.
Here is the outline of your resize function:
create a new canvas with document.createElement("canvas") and a context for the canvas.
create a new Image object and set its .src
create a .onload for the new image that draws the resized image to the canvas using drawImage.
return the new canvas element
Example code and a Demo: http://jsfiddle.net/m1erickson/UTjW8/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var imageSource="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/faces.png";
var canvas=resize(imageSource,125,125);
document.body.appendChild(canvas);
// scale an image to canvas maintaining an aspect ratio
function resize(srcURL,maxWidth,maxHeight){
var tcanvas=document.createElement("canvas");
var tctx=tcanvas.getContext("2d");
var img=new Image();
img.onload=function(){
var iw=img.width;
var ih=img.height;
var ratio = Math.min(maxWidth/iw,maxHeight/ih);
tcanvas.width=iw*ratio;
tcanvas.height=ih*ratio;
tctx.drawImage(img,0,0,iw,ih,0,0,iw*ratio,ih*ratio);
}
img.src=srcURL;
return(tcanvas);
}
}); // end $(function(){});
</script>
</head>
<body>
</body>
</html>
to create a canvas all you have to do is this
var canvas = document.createElement('canvas');
canvas.width = yourwidth;
canvas.height = yourheight;
if you are not asking how to create element just tell me and I'll change the answer
I encountered this problem a week ago. I have tried many methods and finally found solely one method. You can you a uploader which crops & resizes the image and uploads it the to server. The basic idea is that resize the image in the canvas, convert the canvas to a blob for uploading, then upload it in the form. The detailed process is complicated, so there is no free plugin right now.
However, there is a cheap plugin Crop & Upload which can solve your problem easily. I already use it in my website and it runs pretty well.

How can I capture the background of HTML5 Canvas when using toDataURL("image/png")?

I'm creating a collage making application.
This is the code of Canvas. The image is appearing in the background of canvas.
<canvas id="c" width="800" height="600" style="left: -300px; background-image: url('_include/img/Images/rainy_day-1366x768.jpg');"></canvas>
But, when I click on Create Collage button the background is transparent. How can I capture the canvas with background image?
Button click code:
function convertCanvasToImage() {
var canvas = document.getElementById('c');
var image_src = canvas.toDataURL("image/jpeg");
window.open(image_src);
}
I've referred the similar questions and found that we can use or and place Canvas over it. I'm not getting how can I implement that and when I will click on Create Collage button, its gonna capture the background? I'm not sure about it. I'm using Fabric.js
Thanks for any help.
You can't! CSS backgrounds are not part of the canvas (just the element as any background to other elements).
You you need to draw the background onto the canvas instead of using it as a CSS background as this is the only data captured by toDataURL().
If you are using clearRect or fillRect to update the canvas you can consider using drawImage instead with the background image.
Better to use html2canvas script.
The code look like this.
html2canvas($("#c"), {
onrendered: function(canvas) {
var Image1 = canvas.toDataURL("image/jpeg");
window.open(Image1);
}

How do I draw an image loaded from the page in a canvas

I have a html page like this:
<html>
<body>
(1)<canvas id="cs"></canvas>
(2)<img src="/image.png" id="img"/>
</body>
</html>
I would like to know how I could load and display the image (2) in the canvas (1) (with drawImage function).
I tried this but it doesn't work :
var img = $("#img");
ctx.drawImage(img,0,0);
You have to ensure that your image has loaded first. Try wrapping your drawImage call in a ready statment and make certain you are setting up your canvas object first.
$().ready(function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(document.getElementById("img"),0,0);
})
If you haven't already found it here is a nice tutorial: https://developer.mozilla.org/en/Canvas_tutorial/Using_images
Is that all of your code?
You need to set up the canvas first:
var ctx = document.getElementById('cs').getContext('2d');
var img = new Image();
img.src=document.getElementById('img').src;
ctx.drawImage(img,0,0);
Something like that...
Here's an example in jsfiddle: http://jsfiddle.net/vTYqS/
Note that the first picture gets cut off because of the default canvas size. Depending on the image you plan to copy, you may need to resize your canvas like this:
http://jsfiddle.net/vTYqS/1/

Categories

Resources