[英]How to create canvas class with JavaScript ES6?
I want to create a circle using canvas technology, but to do that I want to make use of ES6 features, and try to make an engine like just drawing and updating stuff with Classes.我想使用画布技术创建一个圆,但要做到这一点,我想利用 ES6 特性,并尝试制作一个引擎,就像使用类绘制和更新内容一样。
I'm having a hard time to draw the circle or know how to go about using Classes.我很难画圆圈或知道如何使用类。 I know how to do it in functional programming, but here I'm not sure how that should be achieved.
我知道如何在函数式编程中做到这一点,但在这里我不确定应该如何实现。
I have created somewhat a blueprint, but its far from working I believe.我已经创建了一些蓝图,但我相信它远未奏效。
What can I do to display a circle anywhere on the screen, using Classes for Canvas and the Ufo(circle).我能做些什么来在屏幕上的任何地方显示一个圆圈,使用 Canvas 和 Ufo(circle) 类。
Here is the codepen: https://codepen.io/Aurelian/pen/mGWVbq?editors=1010这是代码笔: https ://codepen.io/Aurelian/pen/mGWVbq ? editors = 1010
Here is the JS:这是JS:
/*
* ------------------------------------------
* *-----------------------------
* Canvas
* *-----------------------------
* ------------------------------------------
*/
// Set
// Draw
// Update
// Animate
class Canvas {
constructor(height, width) {
this.canvas = document.querySelector('canvas');
this.c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
}
Canvas.prototype.draw = function() {
}
Canvas.prototype.animate = function() {
requestAnimationFrame(animate);
new Ufo()
}
/*
* ------------------------------------------
* *-----------------------------
* UFO
* *-----------------------------
* ------------------------------------------
*/
class Ufo {
constructor(x, y, velocity) {
this.x = x,
this.y = y,
this.velocity = {
x: 3,
y: 3
}
}
}
Ufo.prototype.draw = function() {
c.save()
c.beginPath()
c.arc(this.x, this.x, 50, 0, Math.PI * 2, false)
c.fillStyle = red;
c.fill()
c.closePath()
c.restore()
}
Ufo.prototype.update = function() {
Ufo.draw()
}
new Canvas(animate)
You have some mistakes in your code.您的代码中有一些错误。 This is the corrected code:
这是更正后的代码:
'use strict'; /* UFO*/ class Ufo { constructor() { this.x = 77, this.y = 77, this.velocity = { x: 3, y: 3 } } draw(c) { c.save() c.beginPath() c.arc(this.x, this.x, 50, 0, Math.PI * 2, false) c.fillStyle = "red"; c.fill() c.closePath() c.restore() } update(c) { this.draw(c) } } /* Canvas*/ class CanvasDisplay { constructor() { this.canvas = document.querySelector('canvas'); this.ctx = this.canvas.getContext('2d'); this.stageConfig = { width: window.innerWidth, height: window.innerHeight }; this.canvas.width = this.stageConfig.width; this.canvas.height = this.stageConfig.height; this.Ufo = new Ufo(); } animate() { this.ctx.clearRect(0, 0, this.stageConfig.width, this.stageConfig.height); this.Ufo.update(this.ctx) } } let canvasDisplay = new CanvasDisplay(); canvasDisplay.animate();
<canvas></canvas>
I hope you'll find this useful.我希望你会发现这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.