Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Call java putImageData from an HTML tag

Posted on 2012-03-25
4
Medium Priority
?
521 Views
Last Modified: 2012-03-25
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

0
Comment
Question by:thenelson
  • 2
  • 2
4 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 37762891
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
 
LVL 39

Author Comment

by:thenelson
ID: 37763281
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
 
LVL 38

Accepted Solution

by:
Tom Beck earned 2000 total points
ID: 37763394
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
 
LVL 39

Author Closing Comment

by:thenelson
ID: 37763755
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Suggested Courses

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question