Solution 1 :

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>

Problem :

I have the canvas and I want to fill the text on canvas load.My canvas is loaded on dynamically
I have called the onload function for the canvas.But Its not executed

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
function myFunction(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
 ctx.fillText('HTML5 Canvas Tutorial', 10, 50); 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas class="canvas" id="canvas" width="200" height="100"
style="border:1px solid #d3d3d3;" onload="myFunction();"></canvas>

Comments

Comment posted by Menai Ala Eddine – Aladdin

onload

Comment posted by Sphinx

canvas element doesn’t support

Comment posted by stackoverflow.com/questions/22670482/…

Check your [] (