mardi 4 août 2015

Centerize canvas text at all time, even if resized?

I am currently trying to work on this script, which was created by someone else. Yes, I grabbed it, yes I will give credits.

The problem I am having, is trying to center the text even if the window has been resized. When you move the cursor on the text, it explodes randomly. When I resize the window, I need that same text (and those exploded characters) to move. I can easily just put new text in using fillText(), but then I replace the exploded characters.

Obviously I have tried this in my example:

window.onresize = function(event) {
    reload(canvas_id);
}

var reload = function(canvas_id) {
    canvas = document.getElementById(canvas_id);
    context = canvas.getContext("2d");

    canvas.width = window.innerWidth;
}

This resizes the canvas perfectly, but the text won't be centered anymore. To center the text when I place it, I do this:

(window.innerWidth / 2) - (Math.round(bgContext.measureText(keyword).width/2))

bgContext being the canvas.getContext("2d"); obviously.

Here's a JSFiddle showing this issue: http://ift.tt/1gHeNwD



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire