Search code examples
javascripthtml5-canvasdrawimage

JavaScript canvas drawImage not working properly


I'm trying to draw part of an image and it is not work properly. When i try to use it, the width and height not the same as the original.

Here is my code

window.onload = function() {
ImageObjSketch = new Image(); // URL
ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';

canvasClone = document.getElementById("squareTarget");
ctxClone = canvasClone.getContext("2d");
ctxClone.drawImage(ImageObjSketch,34,119,16,16,0,0,38,38);
}
#squareTarget {
	width: 38px; height: 38px;
	position: relative;
	right: 0px;
	display: inline-block;
	border: 1px #000000 solid;
}
<canvas id="squareTarget"></canvas>

As you can see it's not proportional to square, although I set the full size of square.

Another question, as you can see you must run this code twice to see the image, why is that?


Solution

  • You need to specify the size of the canvas explicitly. Then you can get 2d Context:

    window.onload = function() {
    var ImageObjSketch = new Image(); // URL
    ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';
    
    var canvasClone = document.getElementById("squareTarget");
      canvasClone.width = 38;
      canvasClone.height = 38;
      ctxClone = canvasClone.getContext("2d");
    
    
    ctxClone.drawImage(ImageObjSketch, 34,119,16,16,0,0,38,38);
    }
    

    And then your sizing is 38, but you should use the document height and width, but that's a refactor.

    Something like :

    ctxClone.drawImage(ImageObjSketch, 34,119,16,16,0,0,canvasClone.width,canvasClone.height);
    

    https://codepen.io/anon/pen/KoYbzm