<html5> How can export canvas to image(jpg) and pdf file - html

I want to draw image in canvas and export canvas to image(jpg) file and pdf file..
It was.. click download link and popup file save dialog windows..
I have a sample source.. but good run in Chrome, but not running in IE11, IE10, IE9, IE8....
<!DOCTYPE html>
<html>
<head>
<title>toDataURL example</title>
<style>
canvas {
border:solid black 1px;
}
img {
width:400px;
height:400px;
border:solid black 1px;
}
</style>
</head>
<body>
<h1>Copy graphic using toDataURL</h1>
<div>
<button id="copy">Copy canvas image to image element</button> <br />
<canvas id="MyCanvas" width="400" height="400" >This browser or document mode doesn't support canvas</canvas>
<img id="MyPix" src="" width="400" height="400" />
</div>
<script>
// Create some graphics on the canvas.
var canvas = document.getElementById("MyCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.beginPath();
ctx.rect(5, 5, 300, 250);
ctx.fill();
ctx.stroke();
ctx.arc(150, 150, 100, 0, Math.PI, false);
ctx.stroke();
}
// catch the click from the button and copy the graphic
document.getElementById("copy").addEventListener("click", function () {
var canvas1 = document.getElementById("MyCanvas");
if (canvas1.getContext) {
var ctx = canvas1.getContext("2d"); // Get the context for the canvas.
var myImage = canvas1.toDataURL("image/png"); // Get the data as an image.
}
var imageElement = document.getElementById("MyPix"); // Get the img object.
//imageElement.src = myImage; // Set the src to data from the canvas.
window.location = myImage;
}, false);
</script>
</body>
</html>

Use the toDataUrl() function
var datImage = canvas.toDataURL("image/png");
document.write('<img src="'+datImage+'"/>');
This code will take the contents of the canvas, and turn it to a PNG image, and write it onto the screen.
Note: This does not work after you draw an image onto the canvas as it changes the data URL.
Hope this helped!

Related

HTML Canvas, How do you create a circle at the position of the mouse when clicked and then for the circle to increase in radius?

So, I have tried attempting this myself and have searched heavily online and I can't seem to solve this particular issue. I am attempting to make a very simple effect that looks like a very basic water ripple. I intend for the user to be able to click somewhere on the canvas, and for an empty circle (with a black stroke) to appear where the mouse has clicked (starting at a radius of zero), and continuously expand the radius as an animation.
I currently have this code:
<!DOCTYPE html>
<html>
<head>
<!-- Search Engine Optimisation (SEO) -->
<title> Ripple </title>
<meta description="Codelab assignment 3">
<meta keywords="Uni, assignment, ripple, interactive, discovery">
<!-- End of Metadata -->
<!-- Links -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="myCanvas" width="1024" height="768" style="border: 1px solid"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var radius = 0;
//Have a rectangle fill the canvas and add a hit region
//Call the ripple function from the rectangle function
//Track mouse position in rectangle
function ripple(e) {
// ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.arc(e.clientX,e.clientY,radius,0,2*Math.PI);
//ctx.closePath();
ctx.stokeStyle = "black";
ctx.stroke();
radius++;
requestAnimationFrame(ripple);
}
canvas.addEventListener('mousedown', ripple);
</script>
</html>
This is what it currently does:
Screenshot
I really appreciate any help!
You'd have to pass the mouse event when calling the ripple function through requestAnimationFrame.
also, you'll need to set the radius to 0 and clear running animation frame (if any) on mouse click
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var radius = 0;
var rAF;
function ripple(e) {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.arc(e.offsetX, e.offsetY, radius, 0, 2 * Math.PI);
ctx.stokeStyle = "black";
ctx.stroke();
radius++;
rAF = requestAnimationFrame(function() {
ripple(e);
});
}
canvas.addEventListener('mousedown', function(e) {
if (rAF) cancelAnimationFrame(rAF);
radius = 0;
ripple(e);
});
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #ccc}
<canvas id="canvas" width="635" height="208"></canvas>
note: use e.offsetX and e.offsetY to get proper mouse coordinates relative to canvas.

HTML Canvas: How Do I Set Border Restrictions?

I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s and d keys. I am having difficulty figuring out how to have the block not go beyond the borders of the canvas and be restricted only to stay within it.
Here is the part of my code for the canvas:
<html>
<head>
<script>
var positionX=0;
var positionY=0;
window.addEventListener("keydown", onKeyPress, true);
function draw(){
var canvas=document.getElementById("canvas_c");
var context=canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle="green";
context.fillRect(positionX, positionY, 100, 100);
context.strokeStyle = 'black';
context.stroke();
}
function onKeyPress(e){
if (e.keyCode==87){
positionY-=15;
}
if (e.keyCode==83){
positionY+=15;
}
if (e.keyCode==68){
positionX+=50;
}
if (e.keyCode==65){
positionX-=50;
}
draw();
}
</script>
</head>
<body>
<div id="firstDiv">
<canvas id="canvas_c" width="1000" height="500" style="border: 1px solid black;"> </canvas>
</div>
</body>
Here is pseudo-code for the basic boundary respecting movement functions:
// assuming this block object: var block={x:10,y:10,width:20,y:20};
function goLeft(){ if(block.x>0){block.x--;} }
function goUp(){ if(block.y>0){block.y--;} }
function goRight(){ if(block.x<(canvas.width-block.width)){block.x++;} }
function goDown(){ if(block.y<(canvas.height-block.height)){block.y++;} }
[Addition: Here's code based on the code you've added to your question]
Warning: untested code ... may need tweaking! :-)
// save the canvas width & height at the top of the app
var canvas=document.getElementById("canvas1");
var cw=canvas.width;
var ch=canvas.height;
function onKeyPress(e){
if (e.keyCode==87){
positionY=Math.max(0,positionY-15);
}
if (e.keyCode==83){
positionY=Math.min(cw-100,positionY+15);
}
if (e.keyCode==68){
positionX=Math.min(ch-100,positionX+50);
}
if (e.keyCode==65){
positionX=Math.max(0,positionX-50);
}
draw();
}

How to use Data URI to copy canvas as image or another canvas

I converted an image to canvas and made changes to it and want to convert the canvas with changes to a Data URI and use that for the source of image object or another canvas
I am using the following code to do so but do not get any results. Please suggest any other approach I can use.
Code:
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('testImage'); //image object
var canvas = document.getElementById('canvasPnl');// source canvas
var context= canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0,300,300 );
context.fillStyle="#FFFFFF";
context.fillText('Latitude:'+ lat.toString()+'Longitude:'+ lon.toString(),0,10);
context.fillText(new Date(), 0, 20);
context.save();
};
imageObj.src=imageURI;
var img_uri= canvas.toDataURL("image/png");
var image = new Image();
image.src =img_uri;
largeImage.src=img_uri;
var canvas2 = document.getElementById('canvasPnl2');//destination canvas
var context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
}
You've almost got it.
Since you’re generating a second image object (var image), you must also do a second onload:
var imageObj = new Image();
imageObj.onload = function(){
...
var image = new Image();
image.onload=function(){
...
}
image.src=canvas.toDataURL(); // .png is the default
};
imageObj.crossOrigin="anonymous";
imageObj.src=imageURI;
Also, you have a context.save in there without a context.restore (usually they are paired).
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/ne4Up/
<!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; padding:20px; }
canvas{border:1px solid red;}
img{border:1px solid blue;}
</style>
<script>
$(function(){
var lat="lat";
var lon="long";
onPhotoURISuccess("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png");
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('testImage'); //image object
var canvas = document.getElementById('canvasPnl');// source canvas
var context= canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0,100,100 );
context.fillStyle="#FFFFFF";
context.fillText('Latitude:'+ lat.toString()+'Longitude:'+ lon.toString(),0,10);
context.fillText(new Date(), 0, 20);
// context.save(); // where's the matching context.restore();
var image = new Image();
image.onload=function(){
var canvas2 = document.getElementById('canvasPnl2');//destination canvas
var context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
largeImage.src=canvas2.toDataURL();
}
image.src=canvas.toDataURL(); // .png is the default
};
imageObj.crossOrigin="anonymous";
imageObj.src=imageURI;
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Pnl</p>
<canvas id="canvasPnl" width=100 height=100></canvas>
<p>Pnl2</p>
<canvas id="canvasPnl2" width=100 height=100></canvas>
<p>testImage</p>
<img id=testImage src="houseicon.png" width=100 height=100 >
</body>
</html>
If you simply want to draw a canvas onto another canvas there is no need to convert it to image first. Just use the source canvas directly as an argument to drawImage:
context2.drawImage(canvas, 0, 0);
If you absolutely want to convert it to image first you only need to modify a few lines to handle the asynchronous nature of image loading:
var img_uri= canvas.toDataURL("image/png");
var image = new Image();
var canvas2; /// put them here so they are available outside onload below
var context2;
/// put it in a onload here as well
image.onload = function() {
canvas2 = document.getElementById('canvasPnl2');//destination canvas
context2= canvas2.getContext("2d");
context2.drawImage(image,0,0);
}
image.src =img_uri;
A small note: some versions of Chrome has a bug with new Image. For this reason consider using document.createElement('image') instead.

HTML5 Canvas - image not working/showing up in ie10

I have just started looking into html5 and the canvas element and have been trying to create a simple page that rotates an image clockwise and anti clockwise on button clicks. I managed to get something working but i tested it on ie10 and the image is not showing up, just the blank grey canvas. I can only test on ie10 so not sure if this effects other versions too. My full code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<!-- Canvas Element -->
<canvas id="canvas" width="500" height="500" style="background-color: #EAEAEA;">
</canvas>
<!-- Rotate Buttons -->
<h2>Rotate</h2>
<button onclick="rotate('c')">Clockwise</button>
<button onclick="rotate('a')">Anti-Clockwise</button>
<button onclick="rotate('r')">Reset</button>
<script type="text/javascript">
const FPS = 30;
var imagePosX = 90;
var imagePosY = 143;
var imageRot = 0;
var image = new Image();
image.src = "sample.jpg";
var canvas = null;
var context2D = null;
window.onload = startup;
function startup(){
canvas = document.getElementById('canvas');
context2D = canvas.getContext('2d');
setInterval(draw, 500 / FPS);
}
function rotate(d){
setInterval(draw(d), 500 / FPS);
}
function draw(d){
if (d=='a'){imageRot -= 10;}
if (d=='c'){imageRot += 10;}
if (d=='r'){imageRot = 0;}
context2D.clearRect(0, 0, canvas.width, canvas.height);
context2D.save();
context2D.translate(imagePosX+(image.width/2), imagePosY+(image.height/2));
context2D.rotate(imageRot * Math.PI / 180);
// optional shadow
context2D.shadowBlur = 15;
context2D.shadowColor = "rgb(0, 0, 0)";
//
context2D.drawImage(image, 0, 0, image.width, image.height, -(image.width/2), -(image.height/2), image.width, image.height);
context2D.restore();
}
</script>
</body>
</html>
Screenshot of how it should look (and looks in chrome/safari/firefox etc):
Screenshot for ie10:
Can anyone help with what is causing this?
IE 10 doesn't support const. Change it to var. That at least will be one reason for it not working.
Also, the debugger (which is not that amazing in IE10) is still your friend. We'll call him 'semi-friend'. Use him. What does he say?

HTML5 multiple canvas in a page

<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>Animating Sprites In HTML5 Canvas | onlyWebPro.com</title>
</head>
<body>
<canvas id="myCanvas" width="100" height="100">
<!-- Insert fallback content here -->
Sorry, your browser doesn't support canvas technology
</canvas>
<script>
var width = 100,
height = 100,
frames = 4,
currentFrame = 0,
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
image = new Image()
image.src = 'sprite.png';
var draw = function(){
ctx.clearRect(0, 0, width, height);
ctx.drawImage(image, 0, height * currentFrame, width, height, 0, 0, width, height);
if (currentFrame == frames) {
currentFrame = 0;
} else {
currentFrame++;
}
}
setInterval(draw, 100);
</script>
</body>
</html>
The above is the code for creating a canvas which runs a sprite animation sequence in canvas.
Now I want to include another canvas image in same html. when i tried the old one gets replaced so please help me to create another canvas with another image.
Anyone solve it by providing a way to create a multiple canvas in a single HTML page
Add this at html part:
<canvas id="mySecondCanvas" width="100" height="100">
<!-- Insert fallback content here -->
Sorry, your browser still doesn't support canvas technology
</canvas>
And this how you get this canvas with javascript:
var second_canvas = document.getElementById("mySecondCanvas");
:)