gpt4 book ai didi

javascript - 如何使用原型(prototype)模式制作一个 html5 矩形以供重用

转载 作者:行者123 更新时间:2023-11-30 17:41:31 26 4
gpt4 key购买 nike

我试图通过制作矩形对象和矩形实例来使用原型(prototype)模式来理解原型(prototype)继承。看起来很容易,但我不明白。 RectanglePrototype 的方法不是在 Canvas 上绘制矩形。如果我使用与它工作的方法相同的功能。我哪里错了?另外,我知道我需要创建一个初始化函数,但我想我可以在完成第一个基本步骤后稍后再做。

javascript:

    window.onload = function () {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var RectanglePrototype = {
// Properties
x: 0,
y: 0,
width: 100,
height: 100,
color: "white",

// Method
get:function (x, y, width, height, color) {
context.translate(0 , 0);
context.beginPath();
context.rect(x, y, width, height);
context.fillStyle = color;
context.fill();
return this.x, this.y, this.width, this.height, this.color;
}
};

console.log(RectanglePrototype.get);

// Instance of RectanglePrototype
var rectangle1 = Object.create(RectanglePrototype);
rectangle1.x = 200;
rectangle1.y = 100;
rectangle1.width = 300;
rectangle1.height = 150;
rectangle1.color = '#DBE89B';

// Draw Rectangle Function
function rect(x, y, width, height, color) {
context.translate(0 , 0);
context.beginPath();
context.rect(x, y, width, height); // yLoc-canvas.height = -300
context.fillStyle = color;
context.fill();
};

rect(0, 450, 50, 50, '#F7F694');

}
</script>

最佳答案

原型(prototype)是构造函数产生的对象的扩展。在查看原型(prototype)之前,方法查找会遍历对象属性。

我正确的 JS 设计,你只会在你的构造函数中添加非函数属性。

//Your constructor
function Rectangle(){
// Properties
this.x = 0;
this.y = 0;
this.width = 100;
this.height = 100;
this.color = 'red';
}

然后将方法放入原型(prototype)中:

//I prefer the term 'draw'
Rectangle.prototype.draw = function(ctx){
ctx.save();
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
};

然后,在您的项目中使用:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

//List of your shapes to draw on the canvas
var shapes = [];

//Instance of Rectangle
var rectangle1 = new Rectangle();
rectangle1.x = 200;
rectangle1.y = 100;
rectangle1.width = 300;
rectangle1.height = 150;
rectangle1.color = '#DBE89B';
shapes.push(rectangle1);

//Draw your shapes
function draw(){
window.requestAnimationFrame(draw); //See MDN for proper usage, but always request next fram at the start of your draw loop!

for(var i = 0; i<shapes.length; i++){
shapes[i].draw(context);
}
}

这是在 Canvas 上绘图的“正确”方式。对于任何更大的规模,请查看现有的引擎,这些引擎会为您做大量的艰苦工作,并且已经考虑了所有事情,因此您不必这样做。我曾研究过此类引擎。

关于javascript - 如何使用原型(prototype)模式制作一个 html5 矩形以供重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21000738/

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