HTML5 canvas中 drawImage()画图第一次加载只出现最后一个图,刷新就全出现的问题

2025-03-03 04:09:01
推荐回答(2个)
回答1:

必须等到图片完全加载后才能对其进行操作, 浏览器通常会在页面脚本执行的同时异步加载图片。 如果试图在图片未完全加载之前就将其呈现到canvas 上,将不会显示任何图片.

var img= new Image();
img.src = "bark.jpg";

// 图片加载完后,将其显示在canvas 上
img.onload = function () {
drawCanvas();
}

回答2:

var canvas = document.getElementById("canvas");

var context = canvas.getContext('2d');

var drawStop=function(canvas){

var linGrad = context.createLinearGradient(0, 450, 1000, 450);

  linGrad.addColorStop(0.0,"red");

  linGrad.addColorStop(0.5,"yellow");

  linGrad.addColorStop(0.7,"orange");

  linGrad.addColorStop(1.0,"purple");

  context.fillStyle = linGrad;

  context.fillRect(0, 450, 1000, 450);

};


drawStop();


多照着别人的例子照抄几遍就会了,画不出来无非是没获取到id,context,canvas定义出差