帆布有点问题

Little issue with canvas

本文关键字:问题 帆布      更新时间:2023-09-26

我正在尝试运行此代码,其中构造函数是球函数,ball.prototype.draw是原型,应该包括球中的代码。

似乎无法显示球的绘图

var canvas = document.getElementById('ok');
var d = canvas.getContext('2d');
function Ball() {
  ok = 100;
  okk = 100;
};
var circle = function(x, y, radius, fillCircle){
  d.beginPath();
  d.arc(x, y, radius, 0, Math.PI * 2, false);
  if(fillCircle){
    d.fill();
  } else{
    d.stroke(); } };  
Ball.prototype.draw = function() {
  d.lineWidth = 2;
  d.strokeStyle = "black";
  d.fillStyle = "red";
  circle(ok, okk, 30, true); };
Ball.prototype.draw();

在JS中使用原型时,您仍然需要实例化您正在建模的对象的新实例。

所以你的代码很好,除了最后一行;相反,您需要创建一个新球,然后在其上调用成员函数draw,如下所示:

//Ball.prototype.draw();
var ball = new Ball();
ball.draw();