Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Call java putImageData from an HTML tag

Posted on 2012-03-25
4
Medium Priority
?
509 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

886 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