简体   繁体   English

在 html 5 canvas 上添加背景图像

[英]add background image on html 5 canvas

I want to generate a image that can be shared, using HTML 5 canvas, but i'm getting problem to add images canvas:我想使用 HTML 5 canvas 生成可以共享的图像,但是添加图像 canvas 时遇到问题:

here is my code:这是我的代码:

HTML: HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="the_text" style="display: none;width:100%;height:1000px;background-color:red;">
    CERTIFICATE OF ATTENDANCE

  </div>
  <button id="show_img_btn">Search</button>
  <div class=" center-screen" id="show_img_here" style="">

  </div>

</body>

<script async src="https://static.addtoany.com/menu/page.js"></script>

Javascript: Javascript:

window.onload = function() {
  $("#show_img_btn").on("click", function() {
    var canvas = document.createElement("canvas");
    canvas.width = 800;
    canvas.height = 500;
    var ctx = canvas.getContext('2d');

    var img1 = new Image();

    //drawing of the test image - img1
    img1.onload = function() {
      //draw background image
      ctx.drawImage(img1, 0, 0);
      //draw a box over the top
      ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
      ctx.fillRect(0, 0, 800, 500);

    };

    img1.src = 'http://cdn.playbuzz.com/cdn/503aeb8a-c1b8-4679-8ed3-da5e11643f29/8a940ebd-8630-4247-888e-c4c611f4f0e2.jpg';

    // rest of content

    ctx.fillStyle = '#c3d200';
    ctx.font = "45px panton";
    var text = $("#the_text").text();
    ctx.fillText(text, 10, 120);

    ctx.fillStyle = '#000000';
    ctx.font = "17px panton";
    var text = $("#the_text").text();
    ctx.fillText('Lorem ipsum dolor sit amet, consectetur:', 230, 280);

    ctx.fillStyle = '#000000';
    ctx.font = " bold 31px panton";
    var text = $("#the_text").text();
    ctx.fillText('Lorem ipsum dolor sit amet, consectetur', 180, 350);

    ctx.fillStyle = '#000000';
    ctx.font = " bold 31px panton";
    var text = $("#the_text").text();
    ctx.fillText('Lorem ipsum dolor sit amet, consectetur adipiscing', 80, 400);

    // create image
    var img = document.createElement("img");
    img.src = canvas.toDataURL();
    $("#show_img_here").append(img);
    //$("body").append(canvas);
  });
};

// share icons
var a2a_config = a2a_config || {};
a2a_config.overlays = a2a_config.overlays || [];
a2a_config.overlays.push({
  services: ['twitter', 'facebook', 'linkedin', 'email'],
  size: '50',
  style: 'horizontal',
  position: 'top center'
});

CSS: CSS:

body {
  background: white;
}



button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}


.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}

I also tried something like this, but dosent work.我也尝试过类似的方法,但效果不佳。

var background = new Image();
background.src = "http://cdn.playbuzz.com/cdn/503aeb8a-c1b8-4679-8ed3-da5e11643f29/8a940ebd-8630-4247-888e-c4c611f4f0e2.jpg";

background.onload = function(){
    ctx.drawImage(background,0,0);   
}

or draw a image using image source:或使用图像源绘制图像:

var img = document.getElementById("image");
    ctx.drawImage(img, 0, 0);


None of this worked.这些都不起作用。

Note: using tag on html would fix my problem of inserting images, but it will not going to recognize as image to be shared on social networks.注意:在 html 上使用标签可以解决我插入图像的问题,但它不会识别为要在社交网络上共享的图像。

here is the Demo test link: FIDDLE DEMO这是演示测试链接: FIDDLE DEMO

Render content after loading加载后渲染内容

You are rendering content (text) to the canvas and adding that content as an image before the background image has loaded.您正在向 canvas 呈现内容(文本),并在加载背景图像之前将该内容作为图像添加。

Then the background image load event fires and you draw the background image over the content, but as you have already displayed the canvas content (as an image) thus the background image is never displayed.然后触发背景图像加载事件并在内容上绘制背景图像,但是由于您已经显示了 canvas 内容(作为图像),因此永远不会显示背景图像。

Always use the Image.onload event始终使用 Image.onload 事件

When ever you set an Image.src attribute use the load event to start any form of rendering involving that image.每当您设置Image.src属性时,使用 load 事件来启动涉及该图像的任何形式的渲染。

Example例子

Example is taken from your posted code and cut down to show the basics.示例取自您发布的代码并缩减以显示基础知识。 The background image is cross domain which taints the canvas thus example has the final output (as Image) commented out.背景图像是跨域的,它污染了 canvas,因此示例将最终的 output(作为图像)注释掉。 Instead of an image it just adds the canvas when the render is complete.它只是在渲染完成时添加 canvas 而不是图像。

The whole render process is in one function that is called when the background image has loaded.整个渲染过程在一个 function 中,当背景图像加载时调用。

I have removed jQuery as it is irrelevant to the problem and solution.我已删除 jQuery 因为它与问题和解决方案无关。

 show_img_btn.addEventListener("click", function() { const canvas = document.createElement("canvas"); canvas.width = 800; canvas.height = 500; const ctx = canvas.getContext('2d'); const bgImg = new Image(); bgImg.src = 'http://cdn.playbuzz.com/cdn/503aeb8a-c1b8-4679-8ed3-da5e11643f29/8a940ebd-8630-4247-888e-c4c611f4f0e2.jpg'; bgImg.addEventListener("load", () => drawContent(ctx, bgImg), {once: true}); ctx.fillText("Loading image...", 50, 50); }); function drawContent(ctx, bgImg) { ctx.drawImage(bgImg, 0, 0); ctx.fillStyle = "rgba(200, 0, 0, 0.5)"; ctx.fillRect(0, 0, 800, 500); ctx.textAlign = "center"; ctx.fillStyle = '#c3d200'; ctx.font = "45px panton"; ctx.fillText(the_text.textContent, ctx.canvas.width / 2, 120); /* Tainted canvas can not get pixel data on cross origin image (from cdn.playbuzz.com to stackoverflow.com) var img = document.createElement("img"); img.src = ctx.canvas.toDataURL(); img.addEventListener("load", () => { show_img_here.appendChild(img); }, {once: true}); */ show_img_here.appendChild(ctx.canvas); };
 body { background: white; } button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; }
 <div id="the_text" style="display: none;width:100%;height:1000px;background-color:red;">CERTIFICATE OF ATTENDANCE</div> <button id="show_img_btn">Load & create image</button> <div class=" center-screen" id="show_img_here" style=""></div>

i found out that converting the png or jpg file to base64 solved my problem:我发现将 png 或 jpg 文件转换为 base64 解决了我的问题:

  1. by converting to base64 is now possible to transform the canvas to png or jpg;通过转换为 base64 现在可以将 canvas 转换为 png 或 jpg;
  2. the social network icons plug-in is now recognizing the picture as image;社交网络图标插件现在将图片识别为图像;

在此处输入图像描述

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

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