有人可以帮我弄清问题是什么。我收到错误" TypeError:无法读取属性' 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
答案 0 :(得分:0)
可能是因为功能
Maps = function(...) { ... }
不会返回自我对象。
您可能希望将其用作构造函数,因此请使用new运算符更改此行:
var current_map = new Maps("field", "img/dirt.jpeg", 120, 480);
答案 1 :(得分:0)
这是一个工作代码(注释掉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>