gpt4 book ai didi

javascript - 为什么它说我的对象 "ball"不存在方法draw?

转载 作者:行者123 更新时间:2023-11-28 20:00:10 26 4
gpt4 key购买 nike

这是我的代码:

    <!DOCTYPE html>
<html>
<head>
<title>Touch Tracker Marker</title>
<meta name="viewport" content="width=device-width, user-scalable=no">
<style type="text/css">
body { margin: 0px; overflow: hidden; }
canvas { border: 1px solid black; }
</style>
<script type="text/javascript" src="magictouch.js"></script>
<script type="text/javascript">

var canvas;
var ctx;
var w = 0;
var h = 0;

var timer;
var updateStarted = false;
var touches = [];
var balles= [];
function ball(x,y){
this.x=x;
this.y=y;
function draw(){
ctx.beginPath();
ctx.arc(this.x, this.y, 20, 0, 2*Math.PI, true);

ctx.fillStyle = "rgba(0, 0, 200, 0.2)";
ctx.fill();

ctx.lineWidth = 2.0;
ctx.strokeStyle = "rgba(0, 0, 200, 0.8)";
ctx.stroke();
}
};

function update() {
if (updateStarted) return;
updateStarted = true;

var nw = window.innerWidth;
var nh = window.innerHeight;

if ((w != nw) || (h != nh)) {
w = nw;
h = nh;
canvas.style.width = w+'px';
canvas.style.height = h+'px';
canvas.width = w;
canvas.height = h;
}

ctx.clearRect(0, 0, w, h);

var i, len = touches.length;
for (i=0; i<len; i++) {
var touch = touches[i];
var px = touch.pageX;
var py = touch.pageY;

b = new ball(px,py);
b.draw();

console.log('drawn circle at ' + px +',' + py);
}

updateStarted = false;
}

function ol() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
timer = setInterval(update, 15);

canvas.addEventListener('touchend', function() {
ctx.clearRect(0, 0, w, h);
});

canvas.addEventListener('touchmove', function(event) {
event.preventDefault();
touches = event.touches;
});

canvas.addEventListener('touchstart', function(event) {
console.log('start');
});
};

</script>
</head>
<body onload="ol()">

<canvas id="canvas" width="300" height="300" style="top:0px; left:0px; width: 300px; height: 300px;"></canvas>

</body>
</html>

最佳答案

不应该是:

function  ball(x,y){
this.x=x;
this.y=y;
};

ball.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, 20, 0, 2*Math.PI, true);

ctx.fillStyle = "rgba(0, 0, 200, 0.2)";
ctx.fill();

ctx.lineWidth = 2.0;
ctx.strokeStyle = "rgba(0, 0, 200, 0.8)";
ctx.stroke();
}

将函数draw添加到ball.prototype,有效地将其添加到所有ball类型的对象

编辑:在您在评论中提供的链接中,w3schools 添加了这样的功能:

function  ball(x,y){
this.x=x;
this.y=y;
function myFunc() { ... }
this.draw= myFunc;
};

基本上,每次调用 ball 时,它都会创建一个函数对象,并将其附加到名为 draw 的 ball 实例上。这也有效,但我仍然会选择使用原型(prototype),这是在 javascript 中定义方法的正确方法。

将函数添加到原型(prototype)中使得单个函数可用于 ball 的所有实例,而不是为每个 ball 创建一个新的函数对象。

关于javascript - 为什么它说我的对象 "ball"不存在方法draw?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797108/

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