将画布图像复制到框架中

时间:2015-07-17 09:04:59

标签: javascript jquery html5 canvas

作为起点,我的画布上有一个图像:

var canvas = $('canvas')[0];
var ctx=canvas.getContext("2d");
var img=document.getElementById("scream");
   ctx.drawImage(img,0,0,240,297);

现在我想在同一个画布上为此Image添加一个框架。为此:

我首先用图片替换图像

接下来,我尝试复制此框架内的旧画布内容

我尝试这样做:

   var frame = document.getElementById("frame");

   var ctx = $('canvas')[0].getContext("2d");
   var dst = ctx.canvas;

      ctx.drawImage(frame,0,0, 240, 297);
      ctx.drawImage(dst, 40, 40);

代码无效,因为再次将框架复制到画布而不是图片:在这里您可以看到演示:https://jsfiddle.net/35mxfsv0/ < / p>

我错了什么?我需要改变什么?感谢

2 个答案:

答案 0 :(得分:1)

由于您只是将原始canvas分配给dst,当您在该画布上绘制任何内容时,dst也会更改(因为它们指向相同的画布)

所以你必须为dst分配一个新画布,然后将图像从origin绘制到dst,然后在origin上绘制帧,最后画出dst的图像到原点。

&#13;
&#13;
window.onload = function() { // Make it safe that window.onload ensures all images loaded.
  
  var canvas = $('canvas')[0];

  var ctx=canvas.getContext("2d");
  var img=document.getElementById("scream");

  ctx.drawImage(img,0,0,240,297);

  //START OF MY CODE
  var frame = document.getElementById("frame");

  // Comment out as we demo in same scope, ctx is already have what we want.
  //var ctx = $('canvas')[0].getContext("2d");
  // Create a new canvas, and draw the image on the origin canvas to it.
  var dst = document.createElement('canvas');
  dst.width = canvas.width;
  dst.height = canvas.height;
  var dstCtx = dst.getContext('2d');
  dstCtx.drawImage(canvas, 0, 0);
  // Above is what you suppose the canvas should do.
  //var dst = ctx.canvas;        

  // Draw frame
  ctx.drawImage(frame,0,0, 240, 297);

  // As your frame is not an opacity one, you have to copy to specific position.
  ctx.drawImage(dst, 0, 0, dst.width, dst.height, 10, 10, 220, 277);
}
&#13;
img{display:none}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>
    
    <img src="http://www.w3schools.com/tags/img_the_scream.jpg" id="scream"/>
    <img src="http://www.wpclipart.com/page_frames/picture_frames/wood_picture_frame.jpg" id="frame"/>
&#13;
&#13;
&#13;

但是,如果您仍然可以访问该尖叫图像,则可以先绘制帧,然后在其上绘制图像:

var canvas = $('canvas')[0];

var ctx=canvas.getContext("2d");
var img=document.getElementById("scream");
var frame = document.getElementById("frame");

ctx.drawImage(frame,0,0, 240, 297);
// 10, 10 seems to fit the frame.
ctx.drawImage(img, 10, 10);

答案 1 :(得分:0)

请更改html和js文件的ID。