简体   繁体   中英

Drawing image by using Canvas

I have a question regarding to Canvas, here is my code of drawing something:

   .....
   <script>

  function drawImage(imageObj) {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var x = 0;
    var y = 0;

    context.drawImage(imageObj, 0, 0);

    var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
    var data = imageData.data;

    for(var i = 0; i < data.length; i += 4) {
      var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2] + 0.18 * data[i + 3];

      data[i] = brightness;

      data[i + 1] = brightness;

      data[i + 2] = brightness;

      data[i + 3] = brightness;
    }


    context.putImageData(imageData, 0, 0);
  }

  var imageObj = new Image();
  imageObj.onload = function() {
    drawImage(this);
  };
  imageObj.src = 'lena.jpg';
  </script>
.....

This is one part of my code which is Canvas in JavaScript, it instructs the image to be grayscale, it works fine to display the image in the browser, please note the last command is load the image from its source (imageObj.src = 'lena.jpg';), however, when I put this command to the first line in the script, the browser does not show anything, I do not know why it must be in the end of the script, please advise, thanks.

var imageObj = new Image();
  imageObj.onload = function() {
    drawImage(this);
  };
  imageObj.src = 'lena.jpg';

where would the the first line be?

The Script basically the script has 5 lines and starts here like this.

1. var imageObj = new Image();
2. imageObj.onload = function() {
3.   drawImage(this);
4. };
5. imageObj.src = 'lena.jpg';

Puting on the first line would look like this:

imageObj.src = 'lena.jpg';
var imageObj = new Image();
  imageObj.onload = function() {
    drawImage(this);
  };

But the image was not created at that point.

This should work also:

var imageObj = new Image();
imageObj.src = 'lena.jpg';
  imageObj.onload = function() {
    drawImage(this);
  };

The onload function has to be defined before the source. Otherwise it can happen, that the image will be loaded and the onload function is not even defined. Therefore the imageObj.src = 'lena.jpg'; has to be at least after the imageObj.onload .

But you could move that whole block before the drawimage function. that should work fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM