#javascript #php #html #css
#javascript #php #HTML #css — код
Вопрос:
Я пытаюсь добиться обводки текста для своего сайта по созданию мемов. Для английского шрифта это нормально, но не очень хороший результат для неанглийского, потому что обводка контура css идет внутри текста, а не снаружи.
После тестирования многих приемов css я понял, что css не может достичь требуемого текста штриха. Я работаю уже много часов и все еще не могу добиться того, чего хочу получить.
Ниже приведен код моего веб-сайта с обводкой css, и я хочу реализовать код, похожий на этот текст обводки. http://jsfiddle.net/vNWn6 /
Текущее событие с текстом штриха css
$(document).ready(function(){
// canvas related variables
canvas = document.getElementById("mm-canvas");
ctx = canvas.getContext("2d");
imageObj = new Image();
maxFontSize = 60;
MAX_WIDTH = $('#meme-canvas').innerWidth()-20;
MAX_HEIGHT = MAX_WIDTH;
imageObj.onload = function(){
width = imageObj.width;
height = imageObj.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
}
else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
draw();
};
imageObj.src = $(canvas).data('image');
$(document).on('keyup', '.mm-text', function(){
draw();
});
$('#add-textbox').click(function(){
var that = $(this);
var makeid = makeId();
that.parent().before('<div class="form-group mb-form-group"><input type="text" data-position="' makeid '" name="title" placeholder="More Text" class="form-control mm-text pull-left"><div class="mm-spectrum pull-right"><input type="text" value="#fff" class="font" class="form-control"><input type="text" value="#000" class="stroke" class="form-control"></div><div class="clearfix"></div></div>');
$('.resizable:last-child').before('<div id="' makeid '" style="position:absolute; top:' ((canvas.height/2)-50) 'px; width:100%; height:100px; opacity:0.4" class="resizable"></div>');
$('input[data-position="' makeid '"]').next().find('.font').spectrum({
clickoutFiresChange: true,
});
$('input[data-position="' makeid '"]').next().find('.stroke').spectrum({
clickoutFiresChange: true,
});
$("#" makeid).resizable({
containment: ".mm-contain",
stop: function(){ draw(); }
}).draggable({
containment: '.mm-contain',
stop: function(){ draw(); }
});
});
$('.mm-contain').hover(function(){
$('.resizable').toggleClass('ui-state-active');
});
$( ".resizable" ).resizable({
containment: ".mm-contain",
stop: function(){ draw(); }
}).draggable({
containment: '.mm-contain',
stop: function(){ draw(); }
});
$(".font").spectrum({
clickoutFiresChange: true,
});
$(".stroke").spectrum({
clickoutFiresChange: true,
});
$(document).on('change', '.font, .stroke', draw);
});
function makeId(){
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i )
text = possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
// clear the canvas amp; redraw all texts
function draw() {
ctx.save();
ctx.textAlign = "center";
ctx.lineWidth = 1;
ctx.shadowBlur = 1;
ctx.clearRect(0, 0, width, height);
ctx.drawImage(imageObj, 0, 0, width, height);
$('.mm-text').each(function(index){
var that = $(this);
var text = that.val().trim();
var dataPos = that.attr('data-position');
var textboxWidth = $('#' dataPos).innerWidth();
that.attr('data-fontsize', maxFontSize);
var textFont = that.attr('data-fontsize');
ctx.font= textFont "px impact";
var linest = fragmentText(text, textboxWidth-textFont);
if(linest.length == 1){
//maxFontSize = 60;
that.attr('data-fontsize', maxFontSize);
}
if(linest.length == 2){
//maxFontSize = 50;
that.attr('data-fontsize', 50);
}
if(linest.length == 3){
//maxFontSize = 40;
that.attr('data-fontsize', 40);
}
if(linest.length >= 4){
//maxFontSize = 30;
that.attr('data-fontsize', 30);
}
textFont = that.attr('data-fontsize');
ctx.font= textFont "px impact";
ctx.fillStyle = that.next().find('.font').val()
ctx.shadowColor = that.next().find('.stroke').val();
ctx.strokeStyle = that.next().find('.stroke').val();
var lines = fragmentText(text, textboxWidth-textFont);
$('#' dataPos).css('height', parseInt(lines.length*textFont) 'px');
lines.forEach(function(line, i) {
ctx.fillText(line.toUpperCase(), parseInt($('#' dataPos).position().left (textboxWidth/2)), parseInt($('#' dataPos).position().top (i 1) * textFont));
ctx.strokeText(line.toUpperCase(), parseInt($('#' dataPos).position().left (textboxWidth/2)), parseInt($('#' dataPos).position().top (i 1) * textFont));
});
});
}
function fragmentText(text, maxWidth) {
var words = text.toString().split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (words.length > 1) {
words[1] = tmp.slice(-1) words[1];
} else {
words.push(tmp.slice(-1));
}
}
if (ctx.measureText(line words[0]).width < maxWidth) {
line = words.shift() " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}
function saveCanvas()
{
temp_width = MAX_WIDTH;
temp_height = MAX_HEIGHT;
MAX_WIDTH = 500;
MAX_HEIGHT = MAX_WIDTH;
draw();
var canvas = document.getElementById("mm-canvas");
ctx.font = '12px Arial';
ctx.fillStyle = '#fff';
ctx.shadowBlur = 2;
ctx.shadowColor = '#000';
ctx.textAlign = "left";
ctx.fillText(waterMarkText, 3, canvas.height - 3);
var theimage=canvas.toDataURL("image/png");
MAX_WIDTH = temp_width;
MAX_HEIGHT = temp_height;
draw();
$.post(rootURL '/canvas',
{ image: theimage, _token: $('meta[name="_token"]').attr('content') },
function(data){
data = jQuery.parseJSON(data);
if(data.status == 'success')
{
window.location.href = rootURL '/canvas?id=' data.slug;
}
}
);
}
function publishCanvas()
{
MAX_WIDTH = 500;
MAX_HEIGHT = MAX_WIDTH;
draw();
var canvas = document.getElementById("mm-canvas");
var theimage=canvas.toDataURL("image/png");
var ctitle = '';
var form = $('<form action="' rootURL '/create?publish=yes" method="post">'
'<input type="hidden" name="canvas" value="' theimage '" />'
'<input type="hidden" name="ctitle" value="' ctitle '" />'
'<input type="hidden" name="_token" value="' $('meta[name="_token"]').attr('content') '" />'
'</form>');
$('body').append(form);
$(form).submit();
}
Комментарии:
1. Наконец, по крайней мере, я нашел проблему, следуя строке кода.. слой обводки накладывается поверх основного шрифта и приводит к некрасивому результату. Кто-нибудь знает, как я мог бы вернуть слой обводки за текст? ctx.strokeText(line.toUpperCase(), parseInt($(‘#’ dataPos).position().left (textboxWidth/2)), parseInt($(‘#’ dataPos).position().top (i 1) * TextFont));