Canvas How to - Paint text on image top








Question

We would like to know how to paint text on image top.

Answer


<!--from  ww w  .j  a v  a 2  s  .  c  o m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image();
    imageObj.onload = function () {
        var fontSize = 50;
        context.drawImage(imageObj, 0, 0);
        context.font = 'normal ' + fontSize + 'px Arial';
        context.fillText("1AFG", 0, pixelsToPoints(fontSize));
    };
    imageObj.src = 'http://www.java2s.com/style/download.png';
    function pixelsToPoints(pixels) {
        return pixels * 72 / 96;
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: