gpt4 book ai didi

javascript - HTML Canvas 图像 - 在页面中绘制多 Canvas 图像

转载 作者:行者123 更新时间:2023-11-30 16:11:16 27 4
gpt4 key购买 nike

我对 Canvas 有疑问。我可以用单个图像绘制 Canvas ,但我不能用单独的图像绘制每个 Canvas 。- 如果数据只有一个图像,它工作正常,但数据有多个图像,它不工作你能帮帮我吗?

<script>
var h_notepad = 500;
var w_notepad = 737;
var data = [
{dataImageURL: "1_sat_1.png"},
{dataImageURL: "1_sat_2.png"},
{dataImageURL: "1_sat_3.png"},
{dataImageURL: "1_sat_4.png"}
];
for(var i = 0; i < data.length ; i++){

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();

canvas.width = w_notepad;
canvas.height = h_notepad;


img.crossOrigin = 'anonymous';
img.width = w_notepad;
img.height = h_notepad;

console.log(img);
img.onload = function(){
ctx.drawImage(img, 0, 0, w_notepad, h_notepad);
};
img.src = data[i].dataImageURL;

$('body').append(canvas);
}
</script>
<html>
<head>
<meta charset="utf-8">
<title>DRAWING</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<meta charset="utf-8">

</head>
<body>


</body>
</html>

最佳答案

我猜你只得到最后一个。这是一个闭包问题。

load 事件触发时,imgctx 仅引用最后创建的。

因此您在同一 Canvas 上绘制 data.length 时间。

为避免这种情况,您可以使用 this 并将 Canvas 创建包装在 onload 处理程序中:

var imgs = ['http://lorempixel.com/200/300/', 'http://lorempixel.com/500/300/', 'http://lorempixel.com/200/100/'];

for (var i = 0; i < imgs.length; i++) {

var img = new Image();
var width = 500;
var height = 300;

img.onload = function() {
var c = document.createElement('canvas');
c.width = width;
c.height = height;
document.body.appendChild(c);
var ctx = c.getContext('2d');
ctx.drawImage(this, 0,0, width, height);
};

img.src = imgs[i];

}

关于javascript - HTML Canvas 图像 - 在页面中绘制多 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36218037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com