Issue was that the onload
attribute should be used on the body
tag. Move it there and you should be fine. Also, modify your myFunction
function like so to clear the canvas first.
Fixed code:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
function myFunction(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText('HTML5 Canvas Tutorial', 10, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="myFunction();">
<canvas class="canvas" id="canvas" width="200" height="100"
style="border:1px solid #d3d3d3;"></canvas>
</body>