2015-04-03 2 views
0

Я объединил два изображения и некоторый текст, используя html5 canvas, но я не могу поместить изображения так же, как я могу, с текстом. С текстом я просто изменил свойства x и y, чтобы поместить его на холст, но это, похоже, не работает с моими двумя изображениями. Они просто установлены на 0, 0 (вверху слева) независимо.Добавление текста после компоновки изображений, html5 canvas

<canvas width="850" height="450" id="canvas"></canvas> 

<script> 
var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 

var img1 = loadImage('<%= image_url(@entry.picture(:small)) %>', main); 
var img2 = loadImage("<%= image_url('overlay.png') %>", main); 

var imagesLoaded = 0; 
function main() { 
    imagesLoaded += 1; 

    if(imagesLoaded == 2) { 
     // composite now 
     ctx.drawImage(img1, 0, 0); 

     ctx.globalAlpha = 1; 
     ctx.drawImage(img2, 0, 0); 
    } 

} 

function loadImage(src, onload) { 
    var img = new Image(); 

    img.onload = function() { 
     ctx.drawImage(img, 0, 0); 
     ctx.font="30px sans-serif"; 
     ctx.fillText("<%= full_name(@entry.user) %>", 60, 435); 
     ctx.fillStyle="#333333"; 
    }; 
    img.src = src; 

    return img; 

} 
</script> 

В моей голове, линия ctx.drawImage(img1, 0, 0,); должна позиционировать изображение, когда значения 0 и 0 изменяются, но это не так. Мои знания Javascript невелики, поэтому, возможно, что-то очевидное, но я просто не могу понять это. Любая помощь будет принята с благодарностью.

Спасибо.

ответ

1

Есть много стилей кода, используемые для предварительной загрузки изображений, чтобы гарантировать, что они будут полностью загружены, прежде чем пытаться нарисовать их с помощью drawImage:

enter image description here

Вот аннотированный код и демо:

// canvas related variables 
 
var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 
var cw=canvas.width; 
 
var ch=canvas.height; 
 

 
// put the paths to your images in imageURLs[] 
 
var imageURLs=[]; 
 
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face1.png"); 
 
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face2.png"); 
 

 
// the loaded images will be placed in imgs[] 
 
var imgs=[]; 
 
var imagesOK=0; 
 
startLoadingAllImages(imagesAreNowLoaded); 
 

 
// Create a new Image() for each item in imageURLs[] 
 
// When all images are loaded, run the callback (==imagesAreNowLoaded) 
 
function startLoadingAllImages(callback){ 
 

 
    // iterate through the imageURLs array and create new images for each 
 
    for (var i=0; i<imageURLs.length; i++) { 
 
    // create a new image an push it into the imgs[] array 
 
    var img = new Image(); 
 
    imgs.push(img); 
 
    // when this image loads, call this img.onload 
 
    img.onload = function(){ 
 
     // this img loaded, increment the image counter 
 
     imagesOK++; 
 
     // if we've loaded all images, call the callback 
 
     if (imagesOK>=imageURLs.length) { 
 
     callback(); 
 
     } 
 
    }; 
 
    // notify if there's an error 
 
    img.onerror=function(){alert("image load failed");} 
 
    // set img properties 
 
    img.src = imageURLs[i]; 
 
    }  
 
} 
 

 
// All the images are now loaded 
 
// Do drawImage & fillText 
 
function imagesAreNowLoaded(){ 
 

 
    // the imgs[] array now holds fully loaded images 
 
    // the imgs[] are in the same order as imageURLs[] 
 

 
    ctx.font="30px sans-serif"; 
 
    ctx.fillStyle="#333333"; 
 

 
    // drawImage the first image (face1.png) from imgs[0] 
 
    // and fillText its label below the image 
 
    ctx.drawImage(imgs[0],0,10); 
 
    ctx.fillText("face1.png", 0, 135); 
 

 
    // drawImage the first image (face2.png) from imgs[1] 
 
    // and fillText its label below the image 
 
    ctx.drawImage(imgs[1],200,10); 
 
    ctx.fillText("face2.png", 210, 135); 
 

 
}
body{ background-color: ivory; } 
 
#canvas{border:1px solid red;}
<canvas id="canvas" width=350 height=300></canvas>

+1

Спасибо, что нашли время для публикации thi s! Действительно полезно! – abbott567

Смежные вопросы