通过Jquery将图像添加到画布

通过Jquery将图像添加到画布

本文介绍了通过Jquery将图像添加到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像添加到Canvas元素。画布标记:

I'm trying to add an image to an Canvas element. Canvas markup:

<?php foreach($fdsArray as $key => $value):?>
   <div class="design" id="<?php echo $key;?>" data-design="<?php echo $value['url'];?>">
      <canvas width="200" height="200"></canvas>
      <p class="name"><?php echo $value['name'];?></p>
      <p class="asset"><?php echo $value['asset'];?></p>
   </div>
<?php endforeach;?>

Javascript:

Javascript:

<script type="text/javascript">
    $(document).ready(function() {
       $('.design').each(function() {
            var design = $(this).attr('data-design');
            var id = $(this).attr('id');
       });
    });
</script>

我希望图像显示在canvas元素中。 var design包含url。任何人都可以帮我吗?

I want the image to show inside the canvas element. var design contains the url. Could anyone help me out?

推荐答案

尝试

$(document).ready(function() {
  $('.design').each(function() {
    var design = $(this).attr('data-design');
    var id = $(this).attr('id');
    var canvas = $(this).find("canvas")[0];
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.onload = function() {
      ctx.drawImage(this, 0, 0);
    };
    img.src = design;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="design" id="image" data-design="http://lorempixel.com/technics/200/200/">
  <canvas width="200" height="200"></canvas>
  <p class="name">name</p>
  <p class="asset">asset</p>
</div>

这篇关于通过Jquery将图像添加到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 12:51