在html 5画布上添加背景图片 加载后呈现内容始终使用Image.onload事件示例

如何解决在html 5画布上添加背景图片 加载后呈现内容始终使用Image.onload事件示例

我想使用HTML 5 canvas生成可以共享的图像,但是在添加图像canvas时遇到问题:

这是我的代码:

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:

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);
      //draw a box over the top
      ctx.fillStyle = "rgba(200,0.5)";
      ctx.fillRect(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:

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

我也尝试过类似的方法,但是工作量很大。

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);   
}

或使用图像源绘制图像:

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


这些都不起作用。

注意:在html上使用标签可以解决我插入图片的问题,但不会将其识别为要在社交网络上共享的图片。

这是演示测试链接: FIDDLE DEMO

解决方法

加载后呈现内容

您要在画布上渲染内容(文本),然后在加载背景图像之前将该内容作为图像添加。

然后触发背景图像加载事件,并在内容上绘制背景图像,但是由于已经显示了画布内容(作为图像),因此永远不会显示背景图像。

始终使用Image.onload事件

只要您设置了Image.src属性,就可以使用load事件启动涉及该图像的任何形式的渲染。

示例

示例摘自您发布的代码,并进行了缩减以显示基础知识。背景图像是跨域的,弄脏了画布,因此示例的最终输出(如Image)被注释掉了。渲染完成后,仅添加画布而不是图像。

整个渲染过程都在加载背景图片时调用的一个函数中。

我删除了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);
    ctx.fillStyle = "rgba(200,0.5)";
    ctx.fillRect(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>

,

我发现将png或jpg文件转换为base64可以解决我的问题:

  1. 通过转换为base64,现在可以将画布转换为png或jpg;
  2. 社交网络图标插件现在将图片识别为图片;

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-