hello guys I want to load multiple images with JCanvasScript in html5 canvas, but I can't do it. I want to load images side by side in each row. for that I have function loadx(numX, numY) numX - is number of images in a row and numY is number of rows. for example loadX(5,4) or loadX(10,3) is giving me the same result only 1 image.
here is a code
<script>
function init(){
loadx(5, 4);
}
function loadx(numX, numY){
var numTotal = numX * numY;
var imgBMPs = [];
var sliceImg = new Image();
sliceImg.src = "abstract.jpg";
var sliceBmp;
var imgBmp = [];
imgBmp['width'] = sliceImg.width / numX;
imgBmp['height'] = sliceImg.height / numY;
imgBmp['row'] = 0;
imgBmp['y'] = 0;
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
for (a = 0; a < numX; a++){
jc.start('canvas');
imgBmp = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
imgBMPs.push(imgBmp);
jc.start('canvas');
}
}
}
}
</script>
when I tried to debug the code I found out something:
after this
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
I added the code
alert (imgBmp['height']);
and when I refreshed the page First result was the number but other were "Undefined" so what is wrong?
Within your inner for loop you're reassigning the variable imgBmp
to an instance of js.image
. This means that the properties of the original object are lost by the time the loop iterates the second time.
Try updating your code as follows:
<script>
function init(){
loadx(5, 4);
}
function loadx(numX, numY){
var numTotal = numX * numY;
var imgBMPs = [];
var sliceImg = new Image();
sliceImg.src = "abstract.jpg";
var sliceBmp;
/*
// imgBmp is being used as an object not an array
// so the following syntax is usually preferred
var imgBmp = {
width: sliceImg.width / numx,
height: sliceImg.height / numy
}
// and to retrieve a property:
console.log(imgBmp.width);
*/
var imgBmp = [];
imgBmp['width'] = sliceImg.width / numX;
imgBmp['height'] = sliceImg.height / numY;
imgBmp['row'] = 0;
imgBmp['y'] = 0;
sliceImg.onload = function(){
for (i = 0; i < numY; i++){
imgBmp['y'] = i * imgBmp['height'];
for (a = 0; a < numX; a++){
jc.start('canvas');
// create a new variable to hold the instance of jc.image
// so the original object reference is preserved
var jcImage = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
imgBMPs.push(jcImage);
//imgBmp = new jc.image(sliceImg, a * imgBmp['width'], imgBmp['y'], imgBmp['width'], imgBmp['height']);
//imgBMPs.push(imgBmp);
jc.start('canvas');
}
}
}
}
</script>
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.