【发布时间】:2021-09-17 05:40:00
【问题描述】:
我正在尝试在 Angular 9 中单击按钮时清除画布。但单击时显示 ctx.clearcanvas 不是函数。无法实现点击按钮清除画布。
我的控制台出错:ERROR TypeError: ctx.clearCanvas is not a function 在 DrawOnImageComponent_Template_button_click_6_listener 我的 Angular 9 代码如下:
import { Component, OnInit,ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-draw-on-image',
templateUrl: './draw-on-image.component.html',
styleUrls: ['./draw-on-image.component.scss']
})
export class DrawOnImageComponent implements OnInit {
@ViewChild('canvas', {static: false}) canvas: ElementRef;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit(){
let canvas = <HTMLCanvasElement> document.getElementById('canvas');
canvas.width = window.innerWidth - 60;
canvas.height = 400;
let context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0,0 , canvas.width, canvas.height);
let start_background_color = "white";
let draw_color = start_background_color;
let draw_width = 2;
let is_drawing = false;
function change_color(element){
draw_color = element.style.background;
}
canvas.addEventListener("touchstart", start, false);
canvas.addEventListener("touchmove", draw, false);
canvas.addEventListener("mousedown", start, false);
canvas.addEventListener("mousemove", draw, false);
canvas.addEventListener("touchend", stop, false);
canvas.addEventListener("mouseup", stop, false);
canvas.addEventListener("mouseout", stop, false);
function start(event){
is_drawing = true;
context.beginPath();
context.moveTo(event.clientX - canvas.offsetLeft,
event.clientY - canvas.offsetTop);
event.preventDefault();
}
function draw(event){
if(is_drawing == true){
context.lineTo(event.clientX - canvas.offsetLeft,
event.clientY - canvas.offsetTop);
event.strokeStyle = draw_color;
context.lineWidth = draw_width;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
}
event.preventDefault();
}
function stop(event){
if(is_drawing){
context.stroke();
context.closePath();
is_drawing = false;
}
event.preventDefault();
}
function clearCanvas(){
let canvas = <HTMLCanvasElement> document.getElementById('canvas');
let context = canvas.getContext("2d");
context.fillStyle = start_background_color;
context.clearRect(0, 0, canvas.width,canvas.height);
context.fillRect(0, 0, canvas.width,canvas.height);
}
}
<div class="field">
<canvas id="canvas"></canvas>
<div class="tools">
<button type="button" class="button">Undo</button>
<button type="submit" (click)="clearCanvas()">Clear</button>
</div>
</div>
请帮我解决。
【问题讨论】:
标签: javascript html html5-canvas angular9