HTML5 canvas images and canvas text



Drawing canvas images

To draw an image on a canvas, you use the drawImage method of the context object. This method takes an Image object and some (x,y) coordinates to define where the image should be drawn.

The image’s top-left corner is drawn at the specified (x,y). The default size of the image is the actual image size, but you can also resize it.

The following code draws an image on the canvas:

<script type="text/javascript">
    var drawingImage = function () {
        var drawingSurface = document.getElementById("drawingSurface");
        var ctxt = drawingSurface.getContext("2d");
        var img = new Image();
        img.src = "image.jpg";
        img.onload = function () {
            ctxt.drawImage(img, 0, 0);
            ctxt.stroke();
        }
    }
</script>

To reduce the image size by 50 percent replace the drawImage line as in the following code example:

<script type="text/javascript">
    var drawingImageResized = function () {
        var drawingSurface = document.getElementById("drawingSurface");
        var ctxt = drawingSurface.getContext("2d");
        var img = new Image();
        img.src = "image.jpg";
        img.onload = function () {
            ctxt.drawImage(img, 0, 0, img.width * .5, img.height * .5);
            ctxt.stroke();
        }
    }
</script>

Drawing canvas text

Drawing text on the canvas involves adding a few additional tools to your chest from the context object, using the strokeText method and the font property how to apply color to your text and how to manage its alignment.

The following code draws text using strokeText to specify (x,y) coordinates, the font size using font and strokeStyle to specify the color.

<script type="text/javascript">
    var drawingText = function () {
        var drawingSurface = document.getElementById("drawingSurface");
        var ctxt = drawingSurface.getContext("2d");
        ctxt.font = "24px arial";
        ctxt.strokeStyle = "Red";
        ctxt.strokeText("3. Text with altered colored font", 100, 160);
 }
</script>

You can also draw text using fillstyle to specify the color, fillText to specify the (x,y) coordinates and the textAlign to align the text.

The following code draws on the center point of the canvas dividing by 2 the width and the height:

<script type="text/javascript">
    var drawingTextCentered = function () {
        var drawingSurface = document.getElementById("drawingSurface");
        var ctxt = drawingSurface.getContext("2d");
        ctxt.font = "24px arial";
        ctxt.textAlign = "center";
        ctxt.fillStyle = "Red";
        ctxt.fillText("5. Text with altered colored font Centered.", 
             drawingSurface.width / 2, drawingSurface.height / 2);
 }
</script>

Ads Right