Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中实现基于循环的图像放置?_Javascript_Canvas_Html5 Canvas - Fatal编程技术网

如何在javascript中实现基于循环的图像放置?

如何在javascript中实现基于循环的图像放置?,javascript,canvas,html5-canvas,Javascript,Canvas,Html5 Canvas,这是我的剧本 function initCanvas(){ var canvasbg = document.getElementById('canvas_background').getContext('2d'); var imageObj = new Image(); imageObj.src = ""; function drawBox(){ this.x = 0, this.y = 0, this.src = imageObj.src; this.render = fun

这是我的剧本

function initCanvas(){
var canvasbg = document.getElementById('canvas_background').getContext('2d');
var imageObj = new Image();
imageObj.src = "";

function drawBox(){
    this.x = 0, this.y = 0, this.src = imageObj.src;
    this.render = function(){
        canvasbg.drawImage(imageObj, this.x, this.y);
    }
}

var box = new drawBox();
box.src = "Images/Buildings/PokemonCenter.png";
box.x = 50;
box.y = 50;

function animate(){
    box.render();
}

var animateInterval = setInterval(animate, 30);
}

window.addEventListener('load', function(event){
initCanvas();
 });
我试图将src放在
imageObj.src=“Images/Buildings/PokemonCenter.png”下

然后是的,它在那里工作,但是当我试着把它放进盒子里时,它没有出现


有办法吗?因此,我无法用drawImage的大量功能来填充我的脚本,因为在指定drawBox
时没有定义它,所以它没有使用
box.src
显示。你需要重新思考你的结构。更好的方法是使用以下内容:

function drawBox (parameters) {
     this.x = parameters.x || 0, 
     this.y = parameters.y || 0;
     this.image = new Image();
     this.image.src = parameters.src || "";
     this.render = function (canvas) {
         canvas.drawImage(this.image, this.x, this.y);
     }
}

var box = new drawBox({
    x: 50, 
    y: 50,
    src: "https://www.gravatar.com/avatar/b1c8ae5b2e357e18d61bfb0dfd39136c?s=32&d=identicon&r=PG&f=1"
});

function animate(){
    box.render(canvasbg);
}

这样,您就可以将动态参数发送到
drawBox
函数,如果未指定这些参数,它可以返回到默认值。渲染功能也更易于使用,因为您可以在
animate
功能中指定要将图像渲染到的画布。工作小提琴

对不起,我还在学习js,那个“参数”有什么用?我没有遇到过yet@user3323654Javascript中的常见模式是以单个对象的形式传递函数的所有参数。这使得函数调用的代码可读性更好,因为所有参数都已命名。逻辑运算符如何?哦,我明白了!如果没有传递任何值,它的值将为零。它的名称“parameters”是最终的吗?