James
James

Reputation: 5169

Canvas drawImage by points

Is it possible to use canvas.drawImage but supplying dest and source x/y co-ordinates, rather than sizes?

Similar to how Java's drawImage works?

boolean Graphics.drawImage(Image img,
   int dstx1, int dsty1, int dstx2, int dsty2,
   int srcx1, int srcy1, int srcx2, int srcy2,
   ImageObserver observer);

Upvotes: 2

Views: 190

Answers (2)

user1693593
user1693593

Reputation:

Yes, as with the other answers:

drawImage(image,   srcX, srcY, srcW, srcH,   dstX, dstY, dstW, dstH);

So in this case you would have to reverse the order of destination and source as well as calculating the width and height:

boolean Graphics.drawImage(Image img,
   int dstx1, int dsty1, int dstx2, int dsty2,
   int srcx1, int srcy1, int srcx2, int srcy2,
   ImageObserver observer);

Will become:

ctx.drawImage(img, srcx1, srcy1, srcx2 - srcx1, srcy2 - srcy1,
                   dstx1, dsty1, dstx2 - dstx1, dsty2 - dsty1);

or as a wrapper function, parameter-compatible with the Java version:

function drawImage(img, dstx1, dsty1, dstx2, dsty2, srcx1, srcy1, srcx2, srcy2) {
    ctx.drawImage(img, srcx1, srcy1, srcx2-srcx1, srcy2-srcy1,
                       dstx1, dsty1, dstx2-dstx1, dsty2-dsty1);
}

Width and height of 0 is invalid, source must be inside the source image boundaries.

Upvotes: 1

Simon Sarris
Simon Sarris

Reputation: 63812

Yes, Canvas has 3 valid ways to use draw image. Destination x,y, destination x,y, width and height, and those same, plus source x,y, width and height.

So you can do any of the following:

drawImage(image, dx, dy)
drawImage(image, dx, dy, dw, dh)
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

Where s... is source and d... is destination x, y, width and height.

Visual example from the spec:

enter image description here

Upvotes: 0

Related Questions