简体   繁体   English

将具有背景图像和文本内容的画布另存为图像

[英]Save Canvas With Background Image And Text Content As image

How can I save canvas with background data and text content as Image. 如何将带有背景数据和文本内容的画布另存为图像。

I have tried toDataUrl but its returning me only blank canvas. 我尝试过toDataUrl,但它只返回空白画布。

<canvas id="canvas" width="578" height="250" crossOrigin="Anonymous"></canvas>
<a id="link_save" href="https://google.com/" target="_blank">SAVE</a>

<script>

function wrapText(context, text, x, y, maxWidth, lineHeight) {
    var words = text.split(' ');
    var line = '';

    for(var n = 0; n < words.length; n++) {
      var testLine = line + words[n] + ' ';
      var metrics = context.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        context.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      }
      else {
        line = testLine;
      }
    }
    context.fillText(line, x, y);
  }

var canvas = document.getElementById('canvas');
var image = new Image();
image.src = './img/bg.jpg';
var base = canvas.toDataURL();
console.log(base);
image.onload = function () {
var context = canvas.getContext('2d');

var width = 500;
var height = 500;
context.drawImage(image, 10, 0, 300, 200); // resizes image to 300px wide, 200px high


  var maxWidth = 400;
  var lineHeight = 25;
  var x = (canvas.width - maxWidth) / 2;
  var y = 60;
  var text = 'All the world \'s a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.';

  context.font = '16pt Calibri';
  context.fillStyle = '#333';

  wrapText(context, text, x, y, maxWidth, lineHeight);
};

</script>

I have tried saving canvas but only returns blank canvas, not with content. 我尝试保存画布,但仅返回空白画布,不包含内容。

You call canvas.toDataUrl() before the image has been load. 您已加载图像之前调用canvas.toDataUrl()

Put the code at the end of onload event 将代码放在onload事件的末尾

image.onload = function () {

    // Do stuff...

    var base = canvas.toDataURL();
    console.log(base);
}

Another hack: After your done manipulate...just right click in your browser on the canvas and save as .png ;) 另一个技巧:完成操作后……只需在浏览器中的画布上right click ,然后另存为.png;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM