简体   繁体   English

如何使用画布在另一个图像上绘制图像

[英]How to draw an image over another image using canvas

I am working on plotting pinpoint images over another image using canvas. 我正在使用画布在另一个图像上绘制精确图像。 I am new to canvas; 我是新手。 kindly guide me further on this. 请进一步指导我。

I have taken an img element and copied it in a canvas. 我已将一个img元素复制到画布中。 Now I am trying to put another image over that canvas object but it's not working. 现在,我试图在该画布对象上放置另一个图像,但是它不起作用。

Here's my Fiddle . 这是我的小提琴

HTML: HTML:

<p>Image to use:</p>
<img id="scream" src="https://cdn3.iconfinder.com/data/icons/social-media-icons/32/Location-512.png" alt="The Scream" width="220" height="277">

<p>Canvas to fill:</p>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<p><button id="button1">Copy Imange</button></p>
<p><button  id="button2">Draw OVer copied image</button></p> 

Code: 码:

  $("#button1").click(function(){
   var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img,10,10);
  });

    $("#button1").click(function(){
   var c = document.getElementById("myCanvas");
   var ctx = c.getContext("2d");   
    ctx.drawImage("https://cdn3.iconfinder.com/data/icons/social-media-icons/32/Location-512.png",10,10);
  });

There are a couple of issues. 有几个问题。 Firstly, you click events are both looking for the element $("#button1") . 首先,单击事件都在寻找元素$("#button1") I'm assuming the second click event is supposed to be for $("#button2") 我假设第二个点击事件应该是为了$("#button2")

The next problem, in your second click event you are using drawImage from a URL to an image. 下一个问题是,在第二次单击事件中,您正在使用从URL到图像的drawImage You can't do that directly, you need to create a new image and set the source property like so: 您无法直接执行此操作,需要创建一个新图像并按如下所示设置source属性:

var img2 = new Image();
img2.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';

You also shouldn't set the canvas and context on every click, you only need to do that once. 您也不应该在每次点击时都设置画布和上下文,只需要执行一次即可。 Here is the complete example (working example) : 这是完整的示例(工作示例)

$(document).ready(function(){    
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    var img2 = new Image();
    img2.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';

    $("#button1").click(function(){   
        ctx.drawImage(img,10,10);
    });

    $("#button2").click(function(){   
        ctx.drawImage(img2,10,10);
    });
});

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

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