如果您不想使用图片,那么我这里有一个纯编码的示例。正如您所看到的,它需要更多的编码。
index.html
<!doctype html>
<html lang="en">
<head>
<title>Smiley Face</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/smiley.css" >
</head>
<body>
<canvas width="600" height="600" id="smiley">
<p>You need canvas!</p>
<p>This example requires a browser that supports the
<a href="http://www.w3.org/html/wg/html5/">HTML5</a>
<canvas> feature.</p>
</canvas>
<script src="js/smiley.js"></script>
</body>
</html>
smiley.js
class smileyComponent {
constructor() {
this._window = this;
this._cv = document.getElementById('smiley');
this._ctx = this._cv.getContext('2d');
this.drawSmiley();
}
get window() {
return this._window;
}
get cv() {
return this._cv;
}
get ctx() {
return this._ctx;
}
drawArc(x, y, radius, startAngle, endAngle, clockwise) {
this._ctx.arc(x, y, radius, startAngle, endAngle, clockwise);
}
drawLine(xs, ys, xe, ye) {
this._ctx.moveTo(xs, ys);
this._ctx.lineTo(xe, ye);
}
drawSmiley() {
this._ctx.fillStyle = "yellow";
this._ctx.strokeStyle = "black";
this._ctx.lineWidth = 5;
this._ctx.beginPath();
this.drawArc(300,300,200,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
this._ctx.fill();
this._ctx.beginPath();
this.drawArc(200,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
this._ctx.fillStyle = "black";
this._ctx.fill();
this._ctx.beginPath();
this.drawArc(220,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
this._ctx.fillStyle = "white";
this._ctx.fill();
this._ctx.beginPath();
this.drawArc(400,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
this._ctx.fillStyle = "black";
this._ctx.fill();
this._ctx.beginPath();
this.drawArc(420,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
this._ctx.fillStyle = "white";
this._ctx.fill();
this._ctx.beginPath();
this.drawLine(300,350,300,250);
this._ctx.stroke();
this._ctx.beginPath();
this.drawArc(300,300,150,smileyComponent.degreesToRadians(160),smileyComponent.degreesToRadians(380),true);
this._ctx.stroke();
}
static degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
}
window.onload = () => new smileyComponent();
你可以在这里检查结果。