javascript
javascript全栈开发实践-web-7
我們在重構代碼之后,重新添加新的功能:添加一個圓形/橢圓的工具。 第一步,增加一個新的按鈕:
<button id='ellipse' onclick="handleDrawEllipse()">ellipse</button> 復制代碼按鈕點擊事件響應代碼:
function handleDrawEllipse(event) {tool = new EllipseTool(ctx, 2, 'green');} 復制代碼第二部,實現EllipseTool。類似于矩形,也是用鼠標拖出一個矩形區域,然后在這個矩形區域內,畫出一個橢圓/圓形。因此,我們讓EllipseTool直接繼承RectTool:
class EllipseTool extends RectTool {//handleMouseMove(x, y) {if (this._tempImageData) {ctx.putImageData(this._tempImageData, 0, 0);}//this._bottomRight = {x, y};//const pt1 = this._topLeft;const pt2 = this._bottomRight;const left = Math.min(pt1.x, pt2.x);const top = Math.min(pt1.y, pt2.y);const right = Math.max(pt1.x, pt2.x);const bottom = Math.max(pt1.y, pt2.y);//const centerX = (left + right) / 2;const centerY = (top + bottom) / 2;const radiusX = centerX - left;const radiusY = centerY - top;ctx.beginPath();ctx.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, Math.PI * 2);ctx.stroke();}//handleMouseUp() {return new EllipseData(this._topLeft, this._bottomRight, this.lineWidth, this.strokeStyle);}} 復制代碼我們只是重寫了handleMouseMove和handleMouseUp。主要就是覆蓋顯示部分和返回的數據類型。EllipseData也很簡單:
class EllipseData extends RectData {//draw(ctx) {//ctx.beginPath();ctx.lineWidth = this._lineWidth;ctx.strokeStyle = this._strokeStyle;//const pt1 = this._topLeft;const pt2 = this._bottomRight;const left = Math.min(pt1.x, pt2.x);const top = Math.min(pt1.y, pt2.y);const right = Math.max(pt1.x, pt2.x);const bottom = Math.max(pt1.y, pt2.y);//const centerX = (left + right) / 2;const centerY = (top + bottom) / 2;const radiusX = centerX - left;const radiusY = centerY - top;//ctx.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, Math.PI * 2);ctx.stroke();//} 復制代碼同樣,我們讓EllipseData繼承RectData,然后重寫draw方法。當然你也可以讓EllipseData直接繼承自ActionData。并不會有太大的區別。 這樣我們就實現了圓形/橢圓的繪制工具。和重構之前,我們添加矩形工具完全不同,我們沒有修改任何已經存在的代碼,而是僅僅添加了新的代碼,就實現了橢圓工具的添加。 同樣,你也可以繼續實現更多的工具,例如直線,正多邊形,五角星等等。 不過,仍然有可以改進的地方。首先,我們的js代碼和html混在一起,不符合目前主流的方式(html和js分離)。即使我們把js拿出來當獨放在一個文件內,讓然不便與維護。因為所有的功能都混在一個文件內。 接下來,我們將會利用webpack來解決這個問題。讓我們開發js就像c++/java那樣,把代碼分成不同的模塊,然后模塊之間可以進行引用,最后形成一個工程。
轉載于:https://juejin.im/post/5cc2e67af265da037c7cebba
總結
以上是生活随笔為你收集整理的javascript全栈开发实践-web-7的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 光栅图形学算法基础其二 (裁剪算法)
- 下一篇: JS检测浏览器是否最大化