我已经使用html5画布组合了两个图像和一些文本,但我似乎无法以与文本相同的方式定位图像。在文本中我只是更改了x和y属性以将其放置在画布上,但这似乎不适用于我的两个图像。它们只是设置为0,0(左上角)。
<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知识不是很好,所以可能有一些明显的东西,但我无法弄明白。任何帮助将不胜感激。
感谢。
答案 0 :(得分:1)
在尝试使用drawImage
绘制图像之前,有许多样式的代码用于预加载图像以确保它们已完全加载:
这是带注释的代码和演示:
// 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>