1

i new in java script trying to implement flood fill in java script by load image(sketch) from PC to canvas but could not IF anyone can help me i will be very thankful thanks in advance

  • just able to add image to canvas here's my code var can = document.getElementById('canvas'); var ctx = can.getContext('2d'); var img = new Image(); img.onload = function() { can.width = img.width; can.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); } img.src = 'zlati-nathalie.jpg'; – Ali Ahmed Dhillon Jul 29 '16 at 12:31

1 Answers1

0

To draw an image to the canvas, the iamge has to be loaded first. Here is an example on how to draw to the canvas:

var img = new Image();
img.onload = function() {
  //draw after loading
  canvas = document.getElementById('case_canvas');
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
}

img.src = "https://i.stack.imgur.com/xgNw7.png";
//^^ this will start loading the image

fiddle: https://jsfiddle.net/pmeb1uhm/1/

Please notice: you may have issues drawing an image located on your system due to security (cross-origin policy) limitations. You should see an error coming up on your browsers dev-console. Instead of changing your browsers security settings I highly recommend to run your scripts on localhost and load the image using localhost.

Wolfgang
  • 876
  • 5
  • 13
  • thanks it worked for me now can you please help to implement flood fill i will be very thankful – Ali Ahmed Dhillon Jul 29 '16 at 12:46
  • now you have to access the pixel-array to start the algorithm. And this where cross origin policy may cause issues if you're not working on a local server. There are a lot of sources to get started, e.g. http://stackoverflow.com/questions/17714742/looping-through-pixels-in-an-image. The important thing here is: you're getting an array including rows/cols/r,g,b,a values – Wolfgang Jul 29 '16 at 13:43