2 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
x由于您在 ( , y) 位置 ( 100px, 100px) 處繪制了直徑為 的紅色圓圈6px,因此它所占的面積為:
x : 100 - (6 / 2)
y : 100 - (6 / 2)
width : 6
height : 6
您可以使用該方法清除畫布的一部分clearRect。
context.clearRect(97, 97, 6, 6);
如果您的畫布有背景,您將需要清除整個(gè)畫布并重新繪制除紅點(diǎn)以外的所有內(nèi)容,或者您可以調(diào)用fillRect… 假設(shè)它c(diǎn)ontext.fillStyle已設(shè)置為背景色。
context.fillRect(97, 97, 6, 6);
在繪制之前,您必須以某種方式知道紅點(diǎn)的繪制位置(以及它的大?。?。
編輯:在下面的演示之后查看我的 OOP 示例!
演示
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
context.beginPath();
context.arc(100, 100, 3, 0, Math.PI * 2, true); // Outer circle
context.lineWidth = 0;
context.fillStyle = "red";
context.fill();
context.beginPath();
context.arc(36, 100, 3, 0, Math.PI * 2, true); // Outer circle
context.lineWidth = 0;
context.fillStyle = "Orange";
context.fill();
context.beginPath();
context.arc(123, 100, 3, 0, Math.PI * 2, true); // Outer circle
context.lineWidth = 0;
context.fillStyle = "Green";
context.fill();
function removeRedDot() {
context.clearRect(97, 97, 6, 6);
alert('Removed Red Dot');
}
#canvas {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Approach the circle with the mouse</h4> <button onclick="removeRedDot()"> Red Remove Dot</button>
<canvas id="canvas" width=300 height=200></canvas>
OOP 來(lái)拯救!
更好的方法是了解畫布渲染之外的紅點(diǎn)。您可以將畫布上下文包裝在一個(gè)管理圖層和可繪制對(duì)象的類中。
const ctx = document.getElementById('canvas').getContext('2d');
const main = () => {
const canvas = new Canvas(ctx);
const layer = canvas.addLayer();
const circles = [
new Circle({ x: 50, y: 50 }, 3, 'red'),
new Circle({ x: 100, y: 100 }, 6, 'green'),
new Circle({ x: 150, y: 150 }, 12, 'blue')
];
layer.add(...circles);
canvas.render();
// After 2 second, remove the red dot and re-render.
setTimeout(() => {
alert('Removing "red" circle, and adding a "cyan" circle...');
layer.remove(circles[0]);
layer.add(new Circle({ x: 150, y: 50 }, 8, 'cyan'));
canvas.render();
}, 2000);
};
class Drawable {
constructor(origin) {
this.origin = origin;
}
draw(ctx) { }
}
class Layer {
constructor(name) {
this.name = name;
this.drawables = [];
}
add(...drawables) {
drawables.forEach(drawable => this.drawables.push(drawable));
}
remove(drawableOrIndex) {
if (isNaN(drawableOrIndex)) {
drawableOrIndex = this.drawables.indexOf(drawableOrIndex);
}
if (drawableOrIndex > -1) {
this.drawables.splice(drawableOrIndex, 1);
}
}
render(ctx) {
this.drawables.forEach(drawable => drawable.render(ctx));
}
}
class Canvas {
constructor(ctx) {
this.ctx = ctx;
this.layers = [];
}
addLayer(name) {
const newLayer = new Layer(name || 'layer-' + this.layers.length);
this.layers.push(newLayer);
return newLayer;
}
getLayer(nameOrIndex) {
return isNaN(nameOrIndex)
? this.layers.find(layer => layer.name === nameOrIndex)
: this.layers[nameOrIndex];
}
render() {
const { width, height } = this.ctx.canvas;
this.ctx.clearRect(0, 0, width, height);
this.layers.forEach(layer => layer.render(this.ctx));
}
}
class Circle extends Drawable {
constructor(origin, radius, color) {
super(origin);
this.radius = radius;
this.color = color;
}
render(ctx) {
const { x, y } = this.origin;
const diameter = this.radius * 2;
ctx.save();
ctx.beginPath();
ctx.arc(x, y, this.radius, 0, Math.PI * 2, true);
ctx.lineWidth = 0;
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
main();
#canvas {
border: 1px solid black;
}
<canvas id="canvas" width=300 height=200></canvas>

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
由于現(xiàn)有的答案已經(jīng)證明了面向?qū)ο蟮母裱?.....
“我要了一根香蕉,結(jié)果在叢林里遇到了一只拿著香蕉的大猩猩?!?nbsp;,
我添加了這個(gè)答案來(lái)演示更簡(jiǎn)潔的 JavaScript 獨(dú)特的 OO 方法。
原因:與復(fù)雜性的斗爭(zhēng)。
復(fù)雜性是編碼員的頭號(hào)敵人,添加不必要的抽象層、復(fù)制現(xiàn)有行為、預(yù)測(cè)未定義的需求,都會(huì)增加復(fù)雜性。
認(rèn)為如果只有不到 100 行可能無(wú)關(guān)緊要,對(duì)于大型項(xiàng)目,額外的代碼會(huì)很快加起來(lái),每一行都是額外的錯(cuò)誤來(lái)源。
JavaScript 提供了一個(gè)簡(jiǎn)單且非常靈活的 OO 模型,強(qiáng)調(diào)通過(guò)特定對(duì)象構(gòu)造和擴(kuò)展實(shí)現(xiàn)的多態(tài)性。它還具有大量的編碼快捷方式,可以大大減少實(shí)現(xiàn)行為所需的行數(shù)
結(jié)果是功能幾乎相同的代碼減少了一半,
例子
使用
Array
原型實(shí)現(xiàn)層circle
drawable
通過(guò)將類型傳遞給構(gòu)造函數(shù)來(lái)繼承。按
color
, 而不是索引或引用刪除
const ctx = canvas.getContext("2d");
const P2 = (x = 0, y = 0) => ({x,y});
const Drawable = (pos, color, size = 10, type = Circle) => ({pos, size, color, ...type});
const Circle = {
draw(ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
};
const drawables = Object.assign([], {
draw(ctx) { for (const d of this) { d.draw(ctx) } },
remove(color) {
const idx = this.findIndex(d => d.color === color);
return (idx > -1 && (this.splice(idx, 1)[0])) || undefined;
},
}
);
drawables.push(...[...document.querySelectorAll("#buttons button")].map((but, idx)=>
Drawable(P2(100 + idx * 100, 50), but.dataset.color)
));
drawables.draw(ctx);
buttons.addEventListener("click", e => {
if (drawables.remove(e.target.dataset.color)) {
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
drawables.draw(ctx);
}
});
<canvas id="canvas" width="400" height="100"></canvas>
<div id="buttons">
<button data-color="red">Remove Red</button>
<button data-color="green">Remove Green</button>
<button data-color="blue">Remove Blue</button>
</div>
添加回答
舉報(bào)