-2

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?

Joni dep
  • 43
  • 6

1 Answers1

0

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

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • so I assume that the issue happened to me because the canvas doesn't has width and height attribute? Another question, why the code require second refresh? I mean that it doesn't shows the image in first run until you refresh the page. – Joni dep Apr 12 '18 at 15:33
  • Not sure, maybe look into using different event `document.addEventListener('DOMContentLoaded', function() { // your code here }, false);` – Pogrindis Apr 12 '18 at 15:35