简体   繁体   中英

How to load image into canvas on link click

I have multiple links with img src. I want to load each image into the canvas when each link clicked. But it's not work. Here's the script:

JS

var startX = 0,
    startY = 0;

$('.imgLink').click(function(){
    draw($('href'));
});

function draw(image){
    image = image.get(0);
    var ctx = document.getElementById('myCanvas').getContext('2d');
    ctx.drawImage(image,startX,startY,20,20);
    startY+=20;
}

HTML

        <canvas id="myCanvas"></canvas>
<hr />
    <a href="http://www.avatarsdb.com/avatars/blue_eyed_tiger.jpg" class="imgLink">1</a>
    <a href="www.tiger-explorer.com/avatars/Tiger%20Theme/tiger006.jpg" class="imgLink">2</a>
    <a href="http://www.tiger-explorer.com/avatars_uploaded/avatar_522_1369588658.gif" class="imgLink">3</a>
    <a href="www.avatarsdb.com/avatars/angry_tiger.gif" class="imgLink">4</a>
    <a href="http://www.teesnthings.com/ProductImages/animal/wildlife-t-shirts/tiger-t-shirts/striking-tiger-t-shirt.jpg" class="imgLink">5</a>

Here is JSFIDDLE

Three problems:

  1. Make sure all of your links properly have 'http://' in their href
  2. Make sure that the selector is appropriate
  3. You have to load the image into a javascript object in order to dynamically use it
  4. You have to prevent the default method of the link, otherwise, it just opens the link to the image

To correct #2, change your line:

draw($('href'));

into:

draw($(this).attr('href'));

This will properly select the href property you wish to draw to the canvas based on the specific link that was clicked

To correct #3, you can add the following changes:

    var startX = 0,
        startY = 0;

    $('.imgLink').click(function(e){
        e.preventDefault();
        draw($(this).attr('href'));
    });

    function draw(image){
        var newImg = new Image;
        newImg.onload = function() {
        var ctx = document.getElementById('myCanvas').getContext('2d');
        ctx.drawImage(newImg,startX,startY,20,20);
        startY+=20;
          }
        newImg.src = image;


    }

what you are missing is, you need to create an image element and draw it in the canvas, it can be done like:

var startX = 0,
    startY = 0;

$('.imgLink').click(function(e){
    e.preventDefault();
   draw(e.target.href);
});

function draw(src){        
    var ctx = document.getElementById('myCanvas').getContext('2d');
    var img = document.createElement('img');
    img.onload = function(){
    ctx.drawImage(img,startX,startY,20,20);
    startY+=20;
    }
    img.src = src;
}

Fiddle Demo

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