[英]Why do I get "Cannot read property…of undefined with this object?
有人可以帮我找出问题所在。 运行以下代码时,在浏览器中出现错误“ TypeError:无法读取undefined(…)的属性'draw_map'”:
$(document).ready(function() {
Maps = function(id, img_src, width, height) {
var self = {
id: id,
img: new Image(),
width: width,
height: height
}
self.img.src = img_src;
self.draw_map = function() {
ctx.drawImage(self.img, 0, 0, self.img.width, self.img.height, 100, 100, self.img.width * 2, self.img.height * 2);
}
}
function update_canvas() {
current_map.draw_map();
}
///////////////////////////////////////////
// get context to draw on canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Load Image for map
var current_map = Maps("field", "img/dirt.jpeg", 120, 480);
// Drawing
setInterval(update_canvas, 500);
}); // End of Document.ready
可能是因为功能
Maps = function(...) { ... }
不返回自身对象。
可能您想将其用作构造函数,因此请使用new运算符更改此行:
var current_map = new Maps("field", "img/dirt.jpeg", 120, 480);
这是一个工作代码(HTML元素已注释掉)。 问题是您没有在函数构造函数中使用this
引用,然后没有使用new
运算符创建实例。
$(document).ready(function() { Maps = function(id, img_src, width, height) { this.id = id; this.width = width; this.height = height; this.img = new Image() // replace with your Image this.img.src = img_src; var self = this; // Required for the draw_map function this.draw_map = function() { console.log("Draw image", self.img.width, self.img.height); // Uncomment in your code: ctx.drawImage(self.img, 0, 0, self.img.width, self.img.height, 100, 100, self.img.width * 2, self.img.height * 2); } } function update_canvas() { current_map.draw_map(); } /////////////////////////////////////////// // get context to draw on canvas. Uncomment //var canvas = document.getElementById("canvas"); //var ctx = canvas.getContext("2d"); // Load Image for map var current_map = new Maps("field", "img/dirt.jpeg", 120, 480); // Drawing setInterval(update_canvas, 500); }); // End of Document.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.