简体   繁体   中英

Insert an img tag into Canvas element

I'm trying to insert an image into a canvas element. Take this code for exemple ( http://jsfiddle.net/n3L6e1wp/ ). I want to replace the text displayed in the canvas by an img tag. I've tried to replace the content of the div by :

<img src='<%= asset_path('layout/image.jpg') %>' id='picture' style='max-height:100%'>

But nothing displays and I'm not even sure I can do this.

Thanks in advance !

The canvas drawImage method will accept an html img element as an image source, so you can directly do this:

ctx.drawImage(document.getElementById('picture'),0,0);

Example code and a Demo:

 window.onload=function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(document.getElementById('picture'),0,0); } 
 body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; } 
 <canvas id="canvas" width=300 height=300></canvas> <!-- src is for this demo. You can still use your <%...%> --> <img src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png' id='picture' style='max-height:100%'> 

Try this code, will work fine.

var canvas = document.getElementsByTagName('canvas'),
var content = canvas.getContext('2d');

function insertImage() {
  image = new Image();
  image.src = 'assets/img.png';     //any img src
  image.onload = function(){
    content.drawImage(image, 300, 300);
  }
}

insertImage();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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