前端使用canvas在图片上添加水印

<template>
  <div class="canvas">
    <canvas id="img"></canvas>
  </div>
</template>

<script>
export default {
  name: 'home',
  data() {
    return {
      imgUrl: require("../assets/people.png")
    }
  },
  mounted() {
    this.setWatermark('img', this.imgUrl, '图片水印' )
    
  },
  methods: {
    setWatermark(id, imgUrl, str) {
      var canvasImg = document.querySelector(`#${id}`);
      var ctxImg = canvasImg.getContext("2d");
      var img = new Image();
      img.src =imgUrl;
      img.width = 150
      img.height = 200
      canvasImg.width = img.width
      canvasImg.height = img.height
      img.onload = function(){
        ctxImg.drawImage(img, 0, 0, img.width, img.height);

        // 创建水印canvas
        var canvas = document.createElement('canvas');
        canvas.id = "canvas"
        // 设置canvas画布大小
        canvas.width = 80
        canvas.height = 30
    
        var ctx = canvas.getContext('2d')
        
        ctx.rotate(6.10); // 水印旋转角度
        // ctx.translate(0, 0);
        ctx.font = '14px Arial'
        ctx.fillStyle = 'red'
        ctx.fillText(str, 0, 20) // 水印在画布的位置x,y轴
        // ctx.strokeRect(0,0,canvas.width,canvas.height);
        var tamp_w = Math.ceil(canvasImg.width / canvas.width)
        var tamp_h = Math.ceil(canvasImg.height / canvas.height)+2

        for(var i = 0; i < tamp_h; i++) {
          for(var j = 0; j < tamp_w; j++) {
            canvasImg.getContext("2d").drawImage(canvas, j * canvas.width, i* canvas.height)
          }
        }
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.canvas{
  position: relative;
  width: 800px;
  height: 600px;
  background-color: powderblue;
}
</style>

people.PNG
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容