Mathew
Mathew

Reputation: 1430

drawing a cropped version of an image onto a canvas

I have the following html file which draws an image on the canvas.

<canvas id="canvas"width="800"height="800"></canvas>

<script>
    var canvas = document.getElementById('canvas')
    let ctx = canvas.getContext('2d')
    
    let img = new Image()
    img.src = 'https://clipartspub.com/images/circle-clipart-blue-1.jpg'
    img.onload = function(){
        ctx.drawImage(img,300,300,300,300)
    }
</script>

It works fine, however I would like to instead draw a cropped version of this image, for example, the bottom right quarter of the image. Is this possible?

Upvotes: 0

Views: 32

Answers (1)

Akhil
Akhil

Reputation: 879

You have to use the below implementation of drawImage to achieve that

void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

Check the docs here

var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

let img = new Image();
img.src = "https://clipartspub.com/images/circle-clipart-blue-1.jpg";
img.onload = function () {
  const width = img.width;
  const height = img.height;
  ctx.drawImage(
    img, // Source image
    width / 2, // Start at this x of image
    height / 2, // Start at this y of image
    width / 2, // Till this width of image
    height / 2, // Till this height of image
    0, // Start at this x of canvas
    0, // Start at this y of image
    300, // Till this width of canvas
    300 // // Till this height of canvas
  );
};
<canvas id="canvas"width="800"height="800"></canvas>

You can also use canvas.width and canvas.height in the canvas values used above for a better scaled result.

Upvotes: 3

Related Questions