2

Recently I started working on HTML5 Canvas, I'm new to it. I've a problem as follows:

I'm loading a Canvas with Body Chart Image (Predefined Image) and on that User will Draw some lines, shapes, etc.

After that I'll generate an image object as follows

var canvas = document.getElementById("MyCanvas");
var dataURL = canvas.toDataURL();
var image = new Image();
image.src = dataURL;

But, Here it generates only those elements which are drawn by users (lines, shapes) as PNG Image. It won't take that Predefined canvas background Image.

I need to generate a PNG image which should include both the Canvas background Image as well as User entered drawing elements.

How to do this?

Unknown Coder
  • 1,510
  • 2
  • 28
  • 56

2 Answers2

2

Try to actually draw you image onto your canvas, utilizing these functions:

  var canvas = document.getElementById("MyCanvas");
  var img = new Image();
  img.src = 'pathToYourImageHere';
  canvas.drawImage(img,0,0); /* 0,0 is x and y from the top left */

When you now try to save it, it should also save your background image.

EDIT: In response to your comment:

You can circument your layering problem by using two different canvases. One for the image, and one for your drawing. Then layer them on top of each other using absolute positioning. You can read more here: Save many canvas element as image

EDIT2: But actually you shouldn't have a layering problem, since the following code will first draw the image and then draw the arc, and the layering will be fine:

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "somePathToAnImage";
context.drawImage(imageObj, 50, 50);   

var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 1.1 * Math.PI;
var endAngle = 1.9 * Math.PI;
var counterClockwise = false;

context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = "red";
context.stroke();  

Even though the layering is fine, you will be better of by using two canvases, in case you would like to only save the drawing, without the background. You can always save both into a new canvas and save that, when you only use one canvas you'll have a hard time separating the drawing from the background.

Community
  • 1
  • 1
Johannes Lumpe
  • 1,762
  • 13
  • 16
  • I Tried this, It loads with My Predefined Image, But I cant Draw on that. My Drawings will moving under that (Layer problem) – Unknown Coder May 08 '12 at 06:46
0

This is because the image needs time to load, you have to use the onload function.

imgObj.onload = function() { context.drawImage(imageObj, 50, 50); imgLoaded = true;}
if (imgLoaded) { /*you draw shapes here */ }
jazzytomato
  • 6,994
  • 2
  • 31
  • 44