简体   繁体   English

HTML5 Canvas:从形状到对象?

[英]HTML5 Canvas: going from shapes to objects?

I've been tinkering with the html5 canvas element for a while now. 我一直在修补html5 canvas元素一段时间。 It is very useful and all, but I feel very, very limited by the fact that I apparently cannot organize the canvas with objects (not natively). 它非常有用,但是我觉得非常非常有限,因为我显然不能用对象组织画布(不是原生的)。

For instance, if I draw a rectangle, or any other shape, I would really find it useful to be able to access its different properties somewhere else in the script. 例如,如果我绘制一个矩形或任何其他形状,我会发现能够在脚本中的其他位置访问其不同的属性是有用的。 Instead of that, it seems they just remain, well, drawings, and you have to manually keep track of what is on the canvas, and clear it and rewrite it again when you want to change anything. 而不是那样,它们似乎只是保留,好吧,图纸,你必须手动跟踪画布上的内容,并清除它并在你想要改变任何东西时重新重写它。

My question is: am I missing something ? 我的问题是:我错过了什么吗? Is JavaScript providing us with ways to handle objects inside the canvas? JavaScript是否为我们提供了处理画布内对象的方法? If not, are there libraries that do just that already? 如果没有,是否有图书馆已经这样做了? Which one would you say is the best? 你会说哪一个最好?

Canvas aren't really any different from any other drawing-tools. 画布与任何其他绘图工具并没有什么不同。 You really do have to keep track of what you're drawing. 你真的必须跟踪你画的是什么。 The trick is how you do it. 诀窍在于你是如何做到的。 It's actually a pretty good idea to use objects for it and it's not really that hard. 实际上使用对象是一个非常好的主意,并不是那么难。 You just need to pass along the context of the canvas to any object, for it to interact with the canvas and draw on it. 您只需要将画布的context传递给任何对象,以便它与画布交互并在其上绘制。 So if you have an object called Foo you can make the object decide how it wants to be drawn. 因此,如果你有一个名为Foo的对象,你可以让对象决定它是如何绘制的。 For instance it could have a method like so: 例如,它可以有这样的方法:

function Foo() {
  this.draw = function(context) {
    context.restore();
    context.fillStyle = "rgb(200,0,0)";
    context.fillRect (10, 10, 55, 50);
    context.save();
    // And so on...
  }

In your main drawing loop you could have code similar to this: 在主绘图循环中,您可以使用与此类似的代码:

// ... Various init - remember to set the context and store the Foo object somewhere
foo.draw(context);
// ...

This would allow you to create objects with their own methods of drawing. 这将允许您使用自己的绘图方法创建对象。 There are several ways to do it of course, but the advantage of this one is that it's pretty modular. 当然有几种方法可以做到,但这个方法的优点是它非常模块化。 If you want you can have several types of objects that inherit from the same generic type with some nifty tools and so on... Hope that helps! 如果你想要你可以有几种类型的对象继承相同的泛型类型与一些漂亮的工具等等...希望有所帮助!

PS: I just remembered a brilliant tutorial on the whole HTML 5/canvas stuff: It's on MDN here . PS:我刚刚记得关于整个HTML 5 / canvas的精彩教程: 这是在MDN上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM