gpt4 book ai didi

javascript - 从类中移动图像

转载 作者:行者123 更新时间:2023-11-28 02:19:25 25 4
gpt4 key购买 nike

如何从 html5 canvas 中的类访问图像? 我从类加载图像,但要访问它并在 Canvas 上移动它,我无法访问它。我无需上课即可完成此任务。

代码无需类即可正常工作。

          <script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var img1_x=10;
var img1_y=10;
ctx.font="14px Arial";


//this is how you do classes
//this is how you do classes
function ClassLoadImages(name1) {
var img1 = new Image();
this.x=img1_x;
this.y=img1_y;
this.name1=name1;
img1.src = name1;


img1.onload = function() {
ctx.drawImage(img1, img1_x, img1_y);

};

//add this
this.imgElement = img1;
};//func

ClassLoadImages.prototype.m_move = function(){
img1_x++;
img1_y++;
ctx.drawImage(img.imgElement, img1_x, img1_y);
// ctx.fillText("finished loading " ,10,40);
};


function doGameLoop() {

ctx.clearRect(0,0,600,400);
img.m_move();
if (img1_x>30)
{
clearInterval(gameLoop);

}
}




var img= new ClassLoadImages('images/image4.jpg');
gameLoop = setInterval(doGameLoop, 100);
</script>

最佳答案

如果您指的是在构造函数中创建的图像元素,那么您只需将new Image 添加到this:

//this is how you do classes
function ClassLoadImages(name1) {
var img1 = new Image();
this.x=10;
this.y=10;
this.name1=name1;
img1.src = name1;


img1.onload = function() {
ctx.drawImage(img1, img1_x, img1_y);

};

//add this
this.imgElement = img1;
};//func

然后您可以通过 img.imgElement 从对象中引用它。

如果您的意思是无法移动所引用的对象,那么您添加的公共(public)方法中也存在拼写错误 - ClassMoveImages.prototype.m_move 应该是 ClassLoadImages.prototype.m_move 以便访问您创建的对象的属性。

关于javascript - 从类中移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15897386/

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