Arvind A Arvind A - 3 months ago 11
HTML Question

Canvas image drawing is not working

I am trying to draw image using canvas after window loading in Javascript but I could get only a part of an image I could not get the full image.please help me.

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>

window.onload = function() {
drawEx1();
}

var image1 = null;

function drawEx1() {
image1 = new Image();
image1.src =
"file:///C:/Users/Documents/project%20trails/app/i.jpg";
image1.addEventListener('load', drawImage1);
}

function drawImage1() {
var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");

context.drawImage(image1, 10, 10);
}

</script>

</head>
<body >
<div >

<input type="button" id="btn" value="submit" />
<canvas id="canvas1"></canvas>
</div>
</body>
</html>

Answer

Change your drawImage1 function to the following. Run the code snippet below to see in action.

    function drawImage1() {
        var canvas  = document.getElementById("canvas1");
        var context = canvas.getContext("2d");
        canvas.width = 400;
        canvas.height = 400;
        context.drawImage(image1, 0, 0, image1.width, image1.height, 0, 0, 400, 300);
    }

<script>
  window.onload = function() {
    drawEx1();
  }

  var image1 = null;

  function drawEx1() {
    image1 = new Image();
    image1.src =
      "http://img.bleacherreport.net/img/images/photos/003/556/940/edab30087cea36c0ca206fc61a4b10fa_crop_north.jpg?w=630&h=420&q=75";
    image1.addEventListener('load', drawImage1);
  }

  function drawImage1() {
    var canvas = document.getElementById("canvas1");
    var context = canvas.getContext("2d");

    canvas.width = 400;
    canvas.height = 300;
    context.drawImage(image1, 0, 0, image1.width, image1.height, 0, 0, 400, 300);
  }
</script>


<body>
  <div>

    <input type="button" id="btn" value="submit" />
    <canvas id="canvas1"></canvas>
  </div>
</body>