猿问

动态创建的canvas上画图像不显示

我创建了几个canvas,在canvas里又创建了img,然后想让图像画在canvas上,但是只有最有一个显示了。看控制台的时候img标签里是有图片的。


for (n = 0; n<8; n++){

        //在页面中创建canvas

        var oCan = document.createElement('canvas');

        $("#div1").append(oCan);

        var context=oCan.getContext("2d");

        oCan.innerHTML = '<img src="'+ imgSrc[n]+ '" alt=""/>';

        //imgSrc为一个图片src的数组。

        //添加图片

        var image = new Image();

        image.src = imgSrc[n];

        console.log(image);

        image.onload = function () {

            var imgHeight = this.height;

            var imgWidth = this.width;

            imgWidth=oCan.width;

            imgHeight=oCan.height;

            context.drawImage(image, 0, 0,imgWidth,imgHeight);

            var imageData =context.getImageData(0, 0, imgWidth, imgHeight);

            console.log(imageData.data);

         }       

最后显示出来的只有最后一张图片,请问应该怎么改才能全部显示出来?


森栏
浏览 360回答 1
1回答

汪汪一只猫

看注释for (n = 0; n<8; n++){&nbsp; &nbsp; &nbsp; &nbsp; //在页面中创建canvas&nbsp; &nbsp; &nbsp; &nbsp; var oCan = document.createElement('canvas');&nbsp; &nbsp; &nbsp; &nbsp; $("#div1").append(oCan);&nbsp; &nbsp; &nbsp; &nbsp; var context=oCan.getContext("2d");&nbsp; &nbsp; &nbsp; &nbsp; oCan.innerHTML = '<img src="'+ imgSrc[n]+ '" alt=""/>'; //这里是干什么用????&nbsp; &nbsp; &nbsp; &nbsp; //imgSrc为一个图片src的数组。&nbsp; &nbsp; &nbsp; &nbsp; //添加图片&nbsp; &nbsp; &nbsp; &nbsp; var image = new Image();&nbsp; &nbsp; &nbsp; &nbsp; image.src = imgSrc[n];&nbsp; &nbsp; &nbsp; &nbsp; console.log(image);&nbsp; &nbsp; &nbsp; &nbsp; image.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var imgHeight = this.height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var imgWidth = this.width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imgWidth=oCan.width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imgHeight=oCan.height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.drawImage(image, 0, 0,imgWidth,imgHeight); //你把图片始终画在0,0位置,所有图片全覆盖在一起了&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var imageData =context.getImageData(0, 0, imgWidth, imgHeight);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(imageData.data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;&nbsp;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答