我想使用Angular2在某个容器中绘制[input]方块。 你能给我一个简单的例子吗?喜欢使用画布。
到目前为止,我将webpack starter更改为angular:
这是 square.component.template.html :
<h1>My component</h1>
<p>first paragraph</p>
<div class="container">
<form (ngSubmit)="draw(counter.value)" autocomplete="off">
<input [value]="counter.value" (input)="counter.value = $event.target.value" placeholder="Number of squares" autofocus>
<button md-raised-button color="primary">Submit Value</button>
</form>
<canvas width="350" height="800"></canvas>
这是 square.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'square',
templateUrl: './square.component.template.html'
})
export class DetailComponent {
// Set our default values
counter = { value: '' };
constructor() {
}
ngOnInit() {
console.log('hello `Detail` component');
}
draw(value: number) {
console.log('counter', value);
for (var i = 0; i < value; i++) {
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
context.fillStyle = color;
context.fillRect(10, 10, 100, 50);
}
this.counter.value = 0;
}
它画了一个正方形,但只在一个地方。更重要的是,如果我键入值&gt; 50次浏览器崩溃; /我是a2的初学者。你能救我吗?
答案 0 :(得分:0)
您为所有盒子提供相同的位置,以便它们可以在一个位置打印。为此你可以尝试这个
draw(value: number) {
console.log('counter', value);
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");
var topPos = 10;
for (var i = 0; i < value; i++) {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
context.fillStyle = color;
context.fillRect(10, topPos , 100, 50);
topPos = topPos + 55
}
this.counter.value = 0;
}