多个图像未加载到画布上

时间:2016-01-04 17:26:06

标签: javascript html canvas

我使用arc创建了Circle,如下所示。

var startAngle = 0;
var arc = Math.PI / 6;
var ctx;

var leftValue=275;
var topValue=300;	
	   
var wheelImg = ["http://i.stack.imgur.com/wwXlF.png","http://i.stack.imgur.com/wwXlF.png","cat.png","cock.png",
				"croco.png","dog.png","eagle.png","elephant.png","lion.png",
				"monkey.png","rabbit.png","sheep.png"];

function drawWheelImg()
{
	var canvas = document.getElementById("canvas");
  	if(canvas.getContext)
	{
		var outsideRadius = 260;
		var textRadius = 217;
		var insideRadius = 202;

		ctx = canvas.getContext("2d");	

		for(var i = 0; i < 12; i++)
		{
			var angle = startAngle + i * arc;

			ctx.beginPath();
			ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
			ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
			ctx.fill();
			ctx.closePath();
			ctx.beginPath();
			ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
			ctx.shadowBlur=3;
			ctx.shadowColor="#A47C15";
			ctx.stroke();
			ctx.closePath();
			
			ctx.save();
			ctx.translate(leftValue + Math.cos(angle + arc / 2) * textRadius,
						topValue + Math.sin(angle + arc / 2) * textRadius);
			ctx.rotate(angle + arc / 2 + Math.PI / 2);
			var img = new Image();
			
			img.src = wheelImg[i];
			ctx.drawImage(img,-44, -25,50,40);
			ctx.restore();
		}
  	}
}	



function spin()
{
	drawWheelImg();
}

drawWheelImg();
<button class="btnSpin" onclick="spin();">Spin</button>

<canvas id="canvas" width="550" height="580"></canvas>

问题是第一页加载时不会加载。但是当我点击旋转按钮时,它将加载所有图像。

不知道是什么问题。非常感谢任何帮助。

注意: Here in the question同样的问题由img.onload函数解决,但仅适用于单个图片。如果阵列中有多个图像,那么它就无法正常工作。

1 个答案:

答案 0 :(得分:1)

您想要预加载图片。

要执行此操作,您可以在结束</dody>标记之前在页面底部开始加载。

<script>
    // an array of image URLs
    var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
    // an array of images 
    var images = [];
    // for each image name create the image and put it into the images array
    imageNames.forEach(function(name){
        image = new Image();   // create image
        image.src = name;      // set the src
        images.push(image);    // push it onto the image array
    });
</script>         

在使用图像的代码中,您只需要检查它们是否已加载。要执行此操作,只需检查图像complete属性。

// draw the first image in the array
if(images[0].complete){  // has it loaded
    ctx.drawImage(images[0],0,0);  // yes so draw it
}

注意 complete并不意味着已加载。如果您证明网址错误或存在其他错误,则完整标记仍然为真。完成意味着浏览器已完成处理图像。如果图像可能会失败,则必须添加onload事件。

处理错误

如果您不确定图片是否无法加载,则必须制定策略来处理缺失的内容。你需要回答一些问题,我的应用程序可以在没有图像的情况下运行吗?是否有替代来源来获取图像?有没有办法确定这可能发生的频率?我该如何阻止这种情况发生?

在最简单的级别上,您可以通过在onload事件期间将自己的信号量添加到图像对象来标记已加载的图像

    // an array of image URLs
    var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
    // an array of images 
    var images = [];
    // function to flag image as loaded
    function loaded(){
        this.loaded = true;
    }
    // for each image name create the image and put it into the images array
    imageNames.forEach(function(name){
        image = new Image();   // create image
        image.src = name;      // set the src
        image.onload = loaded; // add the image on load event
        images.push(image);    // push it onto the image array
    });

然后在代码中,您将在使用图像之前检查加载的信号量。

// draw the first image in the array
if(images[0].loaded){  // has it loaded
    ctx.drawImage(images[0],0,0);  // yes so draw it
}

关键内容

如果您有应用程序运行所需的图像,那么如果加载图像时出现问题,您应该重定向到错误页面。你可能有几台服务器,所以你也可以在放弃之前尝试不同的资源。

如果您需要停止应用或尝试其他网址,则必须拦截onerror图像事件。

为了简化您对图像的使用(100%确保在该应用运行时加载图像),您应该仅在加载所有图像时启动使用图像的部分。一种方法是计算所有正在加载的图像,并在图像加载时倒计时。当计数器达到零时,您知道所有图像都已加载,然后您可以打电话给您。

以下将加载图像,如果它们失败,它将尝试另一个服务器(源),直到没有更多的选项,您应该重定向到相应的错误页面,以通知客户端猴子已将扳手放入作品。它计算加载图像,当所有图像都已加载时,它将启动应用程序运行,确保所有图像内容都可以安全使用。

    // Server list in order of preferance
    var servers = ["https://fakesiteABC.com/", "http://boogusplace.com/", "http://foobarpoo.com.au/"];

    // an array of image URLs
    var imageNames = ["image1.png", "image2.jpg", ...moreImageNames];
    // an array of images 
    var images = [];
    // loading count tracks the number of images that are being loaded
    var loadingImageCount = 0;
    // function to track loaded images
    function loaded(){
        loadingImageCount -= 1;
        if(loadingImageCount === 0){
              // call your application start all images have loaded
              appStart();
        }
    }
    // function to deal with error
    function loadError(){  // the keyword "this" references the image that generated the event.
        if(this.retry === undefined){  // is this the first error
            this.retry = 1;   // point to the second server
        }else{
            this.retry += 1;  // on each error keep trying servers (locations)
        }
        // are the any other sources to try?
        if(this.retry >= servers.length){  // no 11
            // redirect to error page.
            return;
        }
        // try a new server by setting the source and stripping the 
        // last server name from the previous src URL
        this.src = servers[this.retry] + this.src.replace( servers[ this.retry - 1],"");
        // now wait for load or error
    }


    // for each image name create the image and put it into the images array
    imageNames.forEach(function(name){
        image = new Image();   // create image
        image.src = servers[0] + name;      // set the src from the first server
        image.onload = loaded; // add the image on load event
        image.onerror = loadError; // add the image error handler
        images.push(image);    // push it onto the image array
        loadingImageCount += 1; // count the images being loaded.
    });

还有许多其他策略可以处理缺失的内容。这只是展示了一些使用的机制,并没有定义一个完美的解决方案(没有)