<canvas id="vm" width="300" height="300"></canvas>
<img id ="old" width="300" height="300" src="./img/vumeter.png">
我正在尝试在Typescript中使用canvas draw Image功能。 我有VU表的图片。我想画一个带有值的指针(水平指针),使其可以摆动。
我现在能画出一个摆动的针。但是我无法在图像上绘制canvas元素。我在做什么错了?
export class LevelMeter {
private readonly value: Array < number > ;
ctx: CanvasRenderingContext2D;
constructor(canvas: HTMLCanvasElement, options: Options) {
this.ctx = < CanvasRenderingContext2D > canvas.getContext('2d');
this.img = new Image();
this.img.src = './img/vumeter.png';
this.img.onload = () => window.requestAnimationFrame(this.draw.bind(this));
}
draw() {
let _ctx = this.ctx;
_ctx.drawImage(this.img, 0, 0);
_ctx.fillStyle = 'white';
_ctx.fillRect(0, 0, 500, 500);
_ctx.save();
_ctx.strokeStyle = 'red';
_ctx.translate(150, 180);
_ctx.rotate((Math.PI * ((Math.random() * 0.5) + 1.25)) _ctx.beginPath(); _ctx.moveTo(0, 0); _ctx.lineTo(160, 0);
//_ctx.closePath();
_ctx.stroke(); _ctx.restore();
window.requestAnimationFrame(this.draw.bind(this));
}
}
答案 0 :(得分:1)
您正在通过fillRect调用在图像上绘制白色正方形。
每个帧都从绘制的画布开始(前一帧),您需要开始清除该画布,然后在空画布上绘制图像,最后在其上绘制针:
export class LevelMeter {
private readonly value: Array < number > ;
ctx: CanvasRenderingContext2D;
constructor(canvas: HTMLCanvasElement, options: Options) {
this.ctx = < CanvasRenderingContext2D > canvas.getContext('2d');
this.img = new Image();
this.img.src = './img/vumeter.png';
this.img.onload = () => window.requestAnimationFrame(this.draw.bind(this));
}
draw() {
let _ctx = this.ctx;
_ctx.drawImage(this.img, 0, 0);
_ctx.clearRect(0, 0, 500, 500);
_ctx.save();
_ctx.strokeStyle = 'red';
_ctx.translate(150, 180);
_ctx.rotate((Math.PI * ((Math.random() * 0.5) + 1.25))
_ctx.beginPath(); _ctx.moveTo(0, 0); _ctx.lineTo(160, 0);
//_ctx.closePath();
_ctx.stroke(); _ctx.restore();
window.requestAnimationFrame(this.draw.bind(this));
}
}