大佬,canvas怎么加文字水印啊?

代码如下

<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>

请问老司机怎么将 Hello world 文字直接不通过button点击后显示在图片上,我是做网站图片水印用的,直接打开网站有图片的直接显示 Hello world 文字?还有怎么显示在右下角啊?

效果图
图片描述

阅读 4.1k
1 个回答

看来你对前端一无所知,改成下面:

PS: 请把你的script放到canvas元素的下方

<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>

在线demo地址: https://codepen.io/zhipenglu/...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进