0

assuming I have a sprite map, how can I draw only a part of it using canvas?

For example, I have a 500x500 image but I want to draw only the part from 0 to 50, how can I implement it in JS?

Here's my HTML and Javascript code atm -

<!DOCTYPE HTML>

<html>

<head>
    <meta charset="utf-8" />
    <title>bla bla</title>
    <script>
    window.onload = function() {
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var image = new Image();
        image.src = "gimatrix_letters.png";
        image.onload = function() {
            canvas.width = image.width;
            canvas.height = image.height;
            ctx.drawImage(image, 0, 0); 
        }

    }
    </script>
</head>

<body>
    <canvas id="canvas">
    </canvas>
</body>

</html>

TIA

Yehonatan
  • 3,168
  • 7
  • 31
  • 39
  • Read some documentation: http://www.w3schools.com/tags/canvas_drawimage.asp – enhzflep Dec 05 '14 at 15:29
  • @enhzflep Believe me that I did, but each time that I've tried to implement it, the image got messed up – Yehonatan Dec 05 '14 at 15:31
  • 2
    The documentation is pretty clear on that. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage Read the part about parameters. You want to use `dx`, `dy`, `dWidth` and `dHeight`. – marekful Dec 05 '14 at 15:34
  • @MarcellFülöp - +1 - a much better doc than the one I linked to. The params as needed by the third version of `drawImage` couldn't be clearer imho. – enhzflep Dec 05 '14 at 15:42
  • Though, now when I notice it, the documentation is wrong. The order of args is inncorect – Yehonatan Dec 05 '14 at 16:04

0 Answers0