我想传递一个图像列表并将它们绘制在 Canvas 上。
我的view.py
:
def myview(request):
...
lista=Myobject.objects.filter(tipo=mytipo)
numero_oggetti = range(len(lista))
lista_formattata=[]
for elem in lista:
lista_formattata.append('/media/'+str(elem.myfield))
context_dict['lista']=lista_formattata
context_dict['numero_oggetti']=numero_oggetti
return render(request, 'mytemplate.html', context_dict)
我的template.html
:
<script>
<!--
window.onpageshow = function() {
myfunction({{lista|safe}});
};
-->
</script>
{% for c in numero_oggetti %}
<canvas id='componenti_canvas{{ c }}' width='60' height='75' style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
{% endfor %}
我的script.js
:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.src = lista[i];
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
};
};
此代码有效,但有时图像显示,有时不显示(全部或没有)。当我加载页面时,它们不会显示,当我重新加载页面时,它们会显示。如果我等待几分钟并重新加载,它们就不会再次显示。
我正在使用 Firefox,在控制台日志中,当说 GET image_name.png HTTP/1.0 200
时,它们没有显示(有时它们在缓存中,有时不在……它不显示)没有什么区别),当它什么也没说时,它们就会显示出来。
我尝试过:
-setTimeout
-使用带有 cache: false
、async: false
ajax
请求调用列表
-base.onload
,就像这样:
base.onload = function(){
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
}
但是或者图像永远不会显示或者以这种方式显示。我可以提供细节,当然我也可以做错。
编辑:在评论中说使用onload。
我的script.js
:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.onload = function() {
ctx.drawImage(base, 0, 0);
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
它只在最后一个 Canvas 上绘制最后一个图像(我有很多 Canvas ,我为每个 Canvas 绘制一个图像)。
最佳答案
这不起作用,因为您会在循环的每次迭代中不断覆盖图像。只有一个名为 base 的变量,它只能保存一张图像,因此它之前的所有图像都会丢失。
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image(); // second and more loops you over write base
base.onload = function() {
ctx.drawImage(base, 0, 0); // when it load only the last image is in base
// there is only one var called base so it
// can not hold more than one image
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
使用一个函数来包装所有必需的变量,以便为每个图像创建一个唯一的集合。
function myfunction(lista) {
lista.forEach((name,i)=>{ // each time the call back is called a
// new set of variables are created to
// store each unique image.
var base = new Image();
base.src = name;
base.onload = function() { ctx.drawImage(base, 0, 0); };
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
ctx.scale(0.5,0.5);
});
}
关于javascript - 首次加载的图像不会显示在 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39141233/