我用typescript 声明了一个类 TutuCanvas
import Point from './structs';
class TutuCanvas extends CanvasRenderingContext2D{
private startX:number;
private startY:number;
private isDrawing:boolean=false;
strokeOval(x1:number, y1:number, x2:number, y2:number) :void {
let ox = (x2 - x1) / 2 + x1;
let oy = (y2 - y1) / 2 + y1;
let rx = Math.abs(x2 - x1) / 2;
let ry = Math.abs(y2 - y1) / 2;
this.ellipse(ox, oy, rx, ry, 0, 0, Math.PI * 2);
this.stroke();
}
onDrawStart(coor:Point):void{
this.startX=coor.X;
this.startY=coor.Y;
this.isDrawing=true;
this.beginPath();
this.moveTo(this.startX,this.startY);
}
onDrawing(coor:Point):void{
if(this.isDrawing){
this.lineTo(coor.X,coor.Y);
}
}
onDrawEnd(coor:Point):void{
this.stroke;
this.isDrawing=false;
}
getMouseCoor(mouseCoor:Point):Point {
let coor = this.canvas.getBoundingClientRect()
return {
X: mouseCoor.X - coor.left,
Y: mouseCoor.Y - coor.top
} as Point
}
}
export default TutuCanvas;
然后尝试将系统自带的CanvasRenderingContext2D
强制转换成自己的类:
import TutuCanvas from './TutuCanvas';
let canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('main_canvas');
let ctx: TutuCanvas = <TutuCanvas>canvas.getContext('2d');
canvas.addEventListener('mousedown',function(e:MouseEvent){
ctx.onDrawStart({X:e.clientX,Y:e.clientY});
})
canvas.addEventListener('mousemove',function(e:MouseEvent){
ctx.onDrawing({ X: e.clientX, Y: e.clientY });
})
canvas.addEventListener('mouseup', function (e: MouseEvent){
ctx.onDrawEnd({ X: e.clientX, Y: e.clientY });
})
但是实际编译运行时系统报
Uncaught TypeError: ctx.onDrawing is not a function
然后我看了看编译成的js,它只是把类型去掉了,没有任何类型转换的代码!!!
"use strict";
exports.__esModule = true;
var TutuCanvas_1 = require("./TutuCanvas");
var canvas = document.getElementById('main_canvas');
var ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', function (e) {
ctx.onDrawStart({ X: e.clientX, Y: e.clientY });
});
canvas.addEventListener('mousemove', function (e) {
ctx.onDrawing({ X: e.clientX, Y: e.clientY });
});
canvas.addEventListener('mouseup', function (e) {
ctx.onDrawEnd({ X: e.clientX, Y: e.clientY });
});
要怎么才能解决这个问题呢????
<Type>
和as Type
并不是「转化」,而是断言。只是告诉编译器这里就是
Type
类型。你可以自己写一个转化函数,也可以把
TutuCanvas
写成包装一个普通 ctx 的形式。