我与img src有多个链接。我希望在每个链接点击时将每个图像加载到canvas
。但它不起作用。这是脚本:
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>
这是JSFIDDLE
答案 0 :(得分:1)
三个问题:
要更正#2,请更改您的行:
draw($('href'));
成:
draw($(this).attr('href'));
这将根据点击的特定链接正确选择您想要绘制到画布的href
属性
要更正#3,您可以添加以下更改:
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;
}
答案 1 :(得分:1)
你缺少的是,你需要创建一个图像元素并在画布中绘制它,它可以这样做:
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;
}