Boss, how to add text watermark to canvas?

the code is as follows

<html>
<script>
function watermark(str){
   var img = document.getElementById("img");
   var canvas=document.getElementById("cvs");
   var ctx=canvas.getContext("2d");
   ctx.drawImage(img,0,0);
   ctx.font="20px microsoft yahei";
   ctx.fillStyle = "rgba(255,255,255,0.5)";
   ctx.fillText(str,100,100);
}
</script>
<canvas id="cvs" width="1000" height="500" >
Your browser does not support the HTML5 canvas tag.
</canvas>
<image id="img" src="https://gd1.alicdn.com/imgextra/i2/183574891/TB2fvT9dwjN8KJjSZFgXXbjbVXa_!!183574891.png" > </image>
<button onclick="watermark("Hello world")">add watermark</button>
</html>

I would like to ask the old driver how to directly display the Hello world text on the picture without clicking through button. I am used as a watermark for website pictures. I directly open the Hello world text with pictures on the website. And how is it displayed in the lower right corner?

effect

Apr.05,2021

it seems that you know nothing about the front end. Change it to the following:

PS: Please put your script under the canvas element

<script>
function watermark(str){
   var img = document.getElementById("img");
   var canvas=document.getElementById("cvs");
   var ctx=canvas.getContext("2d");
   ctx.drawImage(img,0,0);
   ctx.font="20px microsoft yahei";
   ctx.fillStyle = "rgba(255,255,255,0.5)";
   ctx.fillText(str,100,100);
}
watermark('Hello world')
</script>

online demo address: https://codepen.io/zhipenglu/.

Menu