Reputation: 6684
I know how to draw in Angular1 Ionic1.
In my html:
<img ng-src="{{image}}" style="width: 100%">
<canvas id="tempCanvas"></canvas>
In my controller
var startimg="img/face.jpg";
$scope.image=startimg;
var canvas = document.getElementById('tempCanvas');
var context = canvas.getContext('2d');
var source = new Image();
source.src = startimg;
canvas.width = source.width;
canvas.height = source.height;
console.log(canvas);
context.drawImage(source,0,0);
context.font = "100px impact";
textWidth = context.measureText($scope.frase).width;
if (textWidth > canvas.offsetWidth) {
context.font = "40px impact";
}
context.textAlign = 'center';
context.fillStyle = 'white';
context.fillText('HELLO WORLD',canvas.width/2,canvas.height*0.8);
var imgURI = canvas.toDataURL();
$timeout( function(){
$scope.image = imgURI;
}, 200);
This code would definitely draw HELLO WORLD text on the top of face image.
However, in Ionic2/Angular2, it seems doesn't work. I can't even get the document.getElementById('tempCanvas')
to work.
Please help.
Thanks.
Upvotes: 1
Views: 7738
Reputation: 214047
You can write the following:
@Component({
selector: 'my-app',
template: `<h1>Angular 2 Systemjs start</h1>
<img [src]="image">
<canvas #layout></canvas>
`
})
export class App {
@ViewChild('layout') canvasRef;
image = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
ngAfterViewInit() {
let canvas = this.canvasRef.nativeElement;
let context = canvas.getContext('2d');
let source = new Image();
source.crossOrigin = 'Anonymous';
source.onload = () => {
canvas.height = source.height;
canvas.width = source.width;
context.drawImage(source, 0, 0);
context.font = "100px impact";
context.textAlign = 'center';
context.fillStyle = 'black';
context.fillText('HELLO WORLD', canvas.width / 2, canvas.height * 0.8);
this.image = canvas.toDataURL();
};
source.src = this.image;
}
}
See also the plunkr https://plnkr.co/edit/qAGyQVqbo3IGSFzC0DcQ?p=preview
Or you can use custom directive like this:
@Directive({
selector: '[draw-text]'
})
class ImageDrawTextDirective {
loaded = false;
@Input() text: String;
@HostListener('load', ['$event.target'])
onLoad(img) {
if(this.loaded) {
return;
}
this.loaded = true;
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
context.drawImage(img, 0, 0);
context.font = "100px impact";
context.textAlign = 'center';
context.fillStyle = 'black';
context.fillText(this.text, canvas.width / 2, canvas.height * 0.8);
img.src = canvas.toDataURL();
}
}
See plunkr for this case https://plnkr.co/edit/BrbAoBlLcbDcx8iDXACv?p=preview
Upvotes: 11