Html Canvas在渲染图像中添加文本或图像

时间:2015-03-09 06:02:29

标签: html5-canvas watermark

我正在尝试在画布生成的图像中添加添加文本(水印)

这是我的代码。

 html2canvas($("#frame"), {
             onrendered: function (canvas) {

                $("#outputImage").html(canvas);

             }

我应该在此代码中添加什么来在生成的图像中添加水印标记

2 个答案:

答案 0 :(得分:3)

在处理程序内部执行以下操作:

html2canvas($("#frame"), {
  onrendered: function (canvas) {

    var ctx = canvas.getContext("2d");       // get 2D context of canvas

    ctx.textBaseline = "top";                // start with drawing text from top
    ctx.font = "20px sans-serif";            // set a font and size
    ctx.fillStyle = "red";                   // set a color for the text
    ctx.fillText("WATERMARK", 20, 20);       // draw the text at some position (x, y)

    $("#outputImage").html(canvas);

  }
}

还有使用以下对齐模式:

ctx.textAlign = "center";  // default: "start" = left-to-right/right-to-left 
                           // depending on language, override with "left" or "right"

答案 1 :(得分:2)

结帐Canvas.globalCompositeOperation。如果将其设置为字符串'lighter',它将使下一个绘图命令(例如fillText())绘制的像素变亮。这是一个样本

<canvas id='canvas'></canvas>
<script>
  var img = new Image();
  img.src = 'http://www.javascripture.com/pic.jpg';
  img.onload = function() {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0, canvas.width, canvas.height);

    // Draw the Watermark
    context.font = '48px sans-serif';
    context.globalCompositeOperation = 'lighter';
    context.fillStyle = '#444';
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillText('watermark', canvas.width / 2, canvas.height / 2);
  };
</script>