簡體   English   中英

在畫布中繪制一個球作為對象

[英]Draw a ball as object in canvas

我已經聲明了下一個正方形,這很簡單,但是現在我想對一個圓做同樣的事情...

我該怎么辦? 謝謝。

//Create Var
var squa = new Square(320, 380, 50, 50);

//Define the square
function Square(x, y, width, height) {
    "use strict";
    this.x = (x === null) ? 0 : x;
    this.y = (y === null) ? 0 : y;
    this.width = (width === null) ? 0 : width;
    this.height = (height === null) ? this.width : height;
}

//Draw the square as object
squa.fill(ctx);

您可以像處理Square一樣進行此操作。 唯一的實際區別是使用arc(x, y, r, startAngle, endAngle)方法。 使用它繪制一個圓,您可以將startAngleendAngle定義為0和2pi。 像這樣: arc(x, y, r, 0, Math.PI*2) 要繪制一個圓,首先需要調用ctx.beginPath(); 說明您將繪制一些路徑或弧線。 例如,這在(100,100)處繪制了一個半徑為10的圓:

ctx.beginPath();
ctx.arc(100, 100, 10, 0, Math.PI*2);
ctx.fill(); // fill() is to fill in the circle, stroke() is for a empty circle.

因此,使用與您上面使用的相同的編碼樣式,這就是制作Circle 如您所見,它幾乎以相同的方式完成。 這是下面的代碼段:

 var ctx = document.getElementById("canvas").getContext("2d"); //Create Var var circ = new Circle(100, 100, 20); //Define the circle function Circle(x, y, r) { "use strict"; this.x = (x === null) ? 0 : x; this.y = (y === null) ? 0 : y; this.r = (r === null) ? 0 : r; this.fill = function(ctx) { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI*2); ctx.fill(); } } //Draw the circle as object circ.fill(ctx); 
 canvas{ border: 1px solid black; } 
 <canvas width=200 height=200 id="canvas"></canvas> 

可以通過使用圓弧(x,y,半徑,起始位置通常為零,終止位置通常為三十六度)來創建一個簡單的圓。

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.beginPath(); context.arc(50, 50, 10, 0, Math.PI*2); context.fillStyle = 'FFF000'; context.fill(); context.closePath(); 
 <canvas id="myCanvas" width="100" height="100"></canvas> 

要將球繪制為對象,只需將其包裝在帶有參數的函數中-x軸,y軸,半徑和球的顏色

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); //invoking the object var cir = new circle(30, 30, 15, '#000FFF'); function circle(x, y, radius, color){ context.beginPath(); context.arc(x, y, radius, 0, Math.PI*2); context.fillStyle = color; context.fill(); context.closePath(); } 
 canvas{ background-color: #fff000; } 
 <canvas id="myCanvas" width="100" height="100"></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM