我一直在尝试使用下面的P5参考中介绍的拖放方法来实现加载画布功能。但是,在将图像拖到画布的第一个实例中,将不会加载图像。第二次尝试将加载好的图像。我尝试加载到画布的每个“新”图像都会发生这种情况。
https://p5js.org/examples/dom-drop.html
当注释掉“ .hide”时,您可以看到图像数据在第一次尝试时已成功加载。我对如何更正此问题感到有些困惑。
谢谢任何能为我指明正确方向的人。
index.html
<!DOCTYPE html>
<html>
<head>
<script src="p5.js"></script>
<script src="p5.dom.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
sketch.js
function setup() {
// create canvas
var c = createCanvas(710, 400);
background(100);
// Add an event for when a file is dropped onto the canvas
c.drop(gotFile);
}
function draw() {
fill(255);
noStroke();
textSize(24);
textAlign(CENTER);
text('Drag an image file onto the canvas.', width/2, height/2);
noLoop();
}
function gotFile(file) {
// If it's an image file
if (file.type === 'image') {
// Create an image DOM element but don't show it
var img = createImg(file.data).hide();
// Draw the image onto the canvas
image(img, 0, 0, width, height);
} else {
println('Not an image file!');
}
}
我的猜测是,这条线需要一些时间来处理背景图像:
var img = createImg(file.data).hide();
因此,当您立即尝试使用时img
,并非总是能完成处理。
image(img, 0, 0, width, height);
一种解决方法是不立即使用img
。这是一个简单的例子:
var img;
function setup() {
var c = createCanvas(710, 400);
c.drop(gotFile);
}
function draw() {
if(img){
image(img, 0, 0, width, height);
}
}
function gotFile(file) {
if (file.type === 'image') {
img = createImg(file.data).hide();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句