Reputation: 4304
I'm trying my hand at creating a tool for users to upload and annotate an image, then save to database. The tool allows drawing lines, adding text and erasing. Now when it comes to adding text,an svg sulution might be better, but haven't found one that dynamically loads a background image.
Anyway, users need to be able to add multiple pieces of text and move them on the image. For this to happen I neede to be able to create layer for the text pieces dynamically, i.e. when the text button is clicked and the text field has some text in it.
At the moment, the text gets added ontop of the canvas in the same position. How can I loop the creation of layers, say in this function:
function draw_text() {
ctx.fillStyle = "blue";
ctx.font = "12pt Helvetica";
ctx.fillText($('#text_entry').val(), 10, 250);
}
Upvotes: 0
Views: 3076
Reputation: 4304
Thanks for you suggestions with this. I decided to implement canvas.js and it's worked out perfectly. Very easy to implement.
Upvotes: 0
Reputation: 9465
I'm not 100% sure what you're asking but I'll give an answer based on your title dynamically create canvas elements.
This is a function I use to create new canvases. Change it to suit your needs.
To use it:
var myCanvas = createLayer(500, 500);
var myContext = myCanvas.getContext('2d');
Function
function createLayer (w, h) {
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
canvas.style.position = "absolute";
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
return canvas;
},
You can then also store the context in an array too allow you to loop through each layer.
Upvotes: 2
Reputation: 98
You can create a Layer object who will have is own draw_text(). All Layers object are push in an array, you goes through to call all render method.
Layer object :
function Layer(_posX, _posY, _text, _context, _font, _color){
this.posX = _posX;
this.poxY = _posY;
this.text = _text;
this.ctx = _context; //canvas context
this.font = _font; //String
this.color = _color; //String "rgb(255, 255, 255)" or "#FFFFFF"
this.draw_text = function(){
this.ctx.fillStyle = this.color;
this.ctx.font = this.font;
this.ctx.fillText(this.text, this.posX, this.posY);
}
Render :
RenderPile = [];
for(elt in RenderPile){
elt.draw_text();
}
Ask questions if I'm not clear.
Upvotes: 1