Cyfer Cyfer - 5 months ago 9
HTML Question

Javascript in general not working

I am having a serious issue in getting Javascript to work at all. It is enabled in my browser (Firefox) and I even tried to test the code in other browsers...
My code is as follows below. What is the issue?

<html>
<head>
<title>DRAW</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
</head>
<body>
<canvas id="draw" height="300" width="300"></canvas>
<script type="text/javascript">
function draw() {
var ctx = document.getElementById('draw').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
}
</script>
</body>
</html>

Answer

Try invoking the function.

You can either call draw() after the function definition, or you can wrap the whole thing as an immediately invoked function like (function...)();

<html>
    <head>
        <title>DRAW</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
    </head>
    <body>
        <canvas id="draw" height="300" width="300"></canvas>
        <script type="text/javascript">
            (function draw() {
            var ctx = document.getElementById('draw').getContext('2d');
            var img = new Image();
            img.onload = function(){
                ctx.drawImage(img,0,0);
                ctx.beginPath();
                ctx.moveTo(30,96);
                ctx.lineTo(70,66);
                ctx.lineTo(103,76);
                ctx.lineTo(170,15);
                ctx.stroke();
            };
            img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
        })();   
    </script>
    </body>
</html>