Use canvas drawImage to split img into two halves

I am trying to split an image on my canvas.

First I declare canvas in HTML:

<canvas width="600" height="400" id="canvas_1">
        Canvas tag not supported
</canvas>

Then I unsuccessfully flatten my image:

var canvas = document.getElementById("canvas_1");

if (canvas.getContext){
   var canvas_context = canvas.getContext("2d");
   var img = document.getElementById("london_eye");
   canvas_context.drawImage(img, 0, 0, 230, 300, 20, 20, 80, 300);
   canvas_context.drawImage(img, 30, 0, 180, 300, 200, 20, 80, 300);
}

I think something is missing there ..

canvas_context.drawImage(img, 0, 0, 230, 300, 20, 20, 80, 300);
canvas_context.drawImage(img, 30, 0, 180, 300, 200, 20, 80, 300);

FIDDLE
Thank you for your time and advice.

+4
source share
1 answer

Original code

var canvas = document.getElementById("canvas_1");

if (canvas.getContext){
  var canvas_context = canvas.getContext("2d");
  var img = document.getElementById("london_eye");
  canvas_context.drawImage(img, 0, 0, 60, 120, 0, 0, 60, 120);
  canvas_context.drawImage(img, 60, 0, 60, 120, 70, 0, 60, 120);
}

image fragments

The last four parameters: destX, destY, destWidth, destHeight. So where on the canvas you want to place these pieces, you can see that the second part is at 70, so its width is 60 first plus a gap of 10.

I set the space to 10 pixels to show two fragments of your img in the fragment!

var i = new Image();
i.crossOrigin = '';
i.onload = function() {
  var canvas = document.getElementById("canvas_1");
    
    if (canvas.getContext){
      var canvas_context = canvas.getContext("2d");
      canvas_context.drawImage(i, 0, 0, 60, 120, 0, 0, 60, 120);
      canvas_context.drawImage(i, 60, 0, 60, 120, 70, 0, 60, 120);
    }
};
i.onerror = function() {
    i.src = 'http://cors.io?u=' + i.src;
    i.onerror = function() {
        document.write('Error loading image');
    }
};
i.src = 'https://i.stack.imgur.com/olfBw.png';
<canvas id="canvas_1"></canvas>
Run codeHide result
+6

Source: https://habr.com/ru/post/1625195/


All Articles