Call java putImageData from an HTML tag

I have HTML canvas javascript code that uses getImageData to save the entire canvas (see code below). I have created a function with putImageData in it so I can call the function from an HTML tag. I made the variables context and ImageData global but I can't get the putImageData to work.  What am I doing wrong? TIA
<a href="#" onclick="clearCanvas()"><img src="clearall.png" width="224" height="56" alt="Clear All" border="0">

var context, ImageData;

var img=new Image();
img.onload = function()
{
   context.drawImage(img,0,0);
   imageData = context.getImageData(0, 0, 700, 643);
   pixels = imageData.data;
};
img.src="PainDiagram.png";

function clearCanvas()
{
   context.putImageData(imageData, 0, 0);
}

Open in new window

LVL 39
thenelsonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tom BeckCommented:
Context is undefined. It should be the context of the canvas you intend to draw the image upon.

context = document.getElementById('canvasId').getContext("2d");

Other than that, your clearCanvas function should work as is.
0
thenelsonAuthor Commented:
I do have context defined:
    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

Open in new window


Here is the entire js file as it is now:
/* © 2009 ROBO Design
 * http://www.robodesign.ro
 */

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {
  var canvas, context, tool;
  var lastX, lastY, prevX, prevY, segCount, reptSeg;


  function init () {
    // Find the canvas element.
    canvas = document.getElementById('imageView');
    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }
	
	var img=new Image();
	img.onload = function(){
	context.drawImage(img,0,0);
	var imageData = context.getImageData(0, 0, 700, 643);
    pixels = imageData.data;
	};
	img.src="PainDiagram.png";

    // Pencil tool instance.
    tool = new tool_pencil();

    // Attach the mousedown, mousemove and mouseup event listeners.
    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);
  }

  // This painting tool works like a drawing pencil which tracks the mouse 
  // movements.
  function tool_pencil () {
    var tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    // This starts the pencil drawing.
    this.mousedown = function (ev) {
			context.lineCap = "round";
			context.strokeStyle = color_value;
			lastX = ev._x;
			lastY = ev._y;
			prevX = ev._x;
			prevY = ev._y;
			segCount = 0;
			if (color_value == "#FF7F50")	 //referred pain
			{
				context.lineWidth = 2;
				reptSeg = 7;
			}
			else
			{
				context.lineWidth = 10;
				reptSeg = 1;
			}
	
	    context.beginPath();
//        context.moveTo(ev._x, ev._y);
        tool.started = true;
    };

    // This function is called every time you move the mouse. Obviously, it only 
    // draws if the tool.started state is set to true (when you are holding down 
    // the mouse button).
    this.mousemove = function (ev) {
		if (tool.started) {
			if(!segCount)
			{
				prevX = lastX;
				prevY = lastY;
				lastX = ev._x;
				lastY = ev._y;
				segCount = reptSeg;
				context.lineTo(ev._x, ev._y);
				context.stroke();
			}
			segCount--;
		}
    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
		if (tool.started) 
		{
			if (color_value == "#FF7F50")
			{
				var angle = Math.atan2(lastY-prevY,lastX-prevX);
		  		context.beginPath();
				context.moveTo(lastX+15*Math.cos(angle),lastY+15*Math.sin(angle));
				context.lineTo(lastX-7*Math.cos(angle-Math.PI/4),lastY-7*Math.sin(angle-Math.PI/4));
		  		context.lineTo(lastX-7*Math.cos(angle+Math.PI/4),lastY-7*Math.sin(angle+Math.PI/4)); 
				context.closePath();
				context . fillStyle  = color_value;
				context.fill();
			}
			tool.started = false;
			tool.mousemove(ev);
			var imageData2 = context.getImageData(0, 0, 700, 643);
			   var newPixels = imageData2.data;
			   for (var i = 0, il = pixels.length; i < il; i += 4) 
			{
			   	if((pixels[i] == 255 && pixels[i+1] == 204 && pixels[i+2] == 153) 
				|| (newPixels[i] > 235 && newPixels[i+1] < 150 && newPixels[i+2] > 75 && newPixels[i+2] < 110))
				{
				}
				else
			 		{	
			           newPixels[i] = pixels[i];
			           newPixels[i+1] = pixels[i+1];
			           newPixels[i+2] = pixels[i+2];
			   	}
			   }
			   context.putImageData(imageData2, 0, 0);
			   //document.form.output.value = document.form.output.value + " x= " + ev._x + ",  y= " + ev._y + "\nLX= " + lastX + ", LY= " + lastY +  "\npX= " + prevX + ", pY= " + prevY + "\nsegCount= " + segCount + "\n\n";
		}
    };
  }

  // The general-purpose event handler. This function just determines the mouse 
  // position relative to the canvas element.
  
 
  function ev_canvas (ev) {
    if (ev.offsetX || ev.offsetX == 0) { // Opera and WebKit
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }  
    else if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } 

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }
  }

  init();
  

}, false); }


// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:

Open in new window

0
Tom BeckCommented:
Works fine. As long as you are not re-declaring imageData as in line 35:

var imageData = context.getImageData(0, 0, 700, 643);

Or context as in line 8:

var canvas, context, tool;

And your two variables, context and imageData, are declared first outside of all functions.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
thenelsonAuthor Commented:
I got it working.  I didn't make the declarations of imageData and context truly global before - they were in a function.

Thanks again!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.