使用js函数更新ctx.textAlign

时间:2016-05-22 08:12:17

标签: javascript canvas

嗨,我有这个js函数:

function ChangeTextAlign(selectTag) {
    // Returns the index of the selected option
    var whichSelected = selectTag.selectedIndex;

    // Returns the text of the selected option
    var alignValue = selectTag.options[whichSelected].text;

    var div = document.getElementById("first-text");
    div.style.textAlign = alignValue;
}

此功能在输入字段中完美更新文本对齐:

<input type='text' value='Pirma eilutė' id='first-text' />

但是如何使它与ctx.textAlign一起使用?以下是它现在的设置方式:

 ctx.font = '12pt sans-serif';
 ctx.strokeStyle = '#929292';
 ctx.fillStyle = '#929292';
 ctx.textAlign = 'center';
 ctx.textBaseline = 'top';

每次按下其中一个选项时,我想更新ctx.textAlign值:

更改textAlign值:

 <select onchange="ChangeTextAlign (this);" size="4">
     <option />left
     <option />right
     <option selected="selected" />center
     <option />justify
 </select>

这仅适用于我的输入字段,但我想更新ctx.textAlign的值。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

鉴于此html:

<select id='align' size="4">
    <option value='left'/>left
    <option value='right'/>right
    <option value='center' selected="selected" />center
    <option value='justify' />justify
</select>

在您的选择元素上收听change个事件:

var selection=document.getElementById('align');
selection.onchange=function(e){ChangeTextAlign(e);};

选择更改:

  • 获取用户选择的对齐值
  • context.textAlign设为该值
  • 清除画布
  • 重绘文本以使用所选对齐方式显示

javascript change处理程序:

function ChangeTextAlign(event){
    var newAlignment=selection.value;
    if(newAlignment=='justify'){alert('Justify is not supported'); return;}
    ctx.textAlign=newAlignment;
    redraw(text);
}

示例代码和演示:

&#13;
&#13;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;

var text = 'Hello, World!'
ctx.textAlign = 'center';

redraw(text);

var selection = document.getElementById('align');
selection.onchange = function(e) {
  ChangeTextAlign(e);
};

function ChangeTextAlign(event) {
  var newAlignment = selection.value;
  if (newAlignment == 'justify') {
    alert('Justify is not supported');
    return;
  }
  ctx.textAlign = newAlignment;
  redraw(text);
}

function redraw(text) {
  // clear the canvas
  ctx.clearRect(0, 0, cw, ch);
  // demo only, show the fillText x,y
  ctx.fillRect(cw / 2, 0, 1, ch);
  // draw the text
  ctx.fillText(text, cw / 2, ch / 2);
}
&#13;
body {
  background-color: ivory;
}
#canvas {
  border: 1px solid red;
  margin: 0 auto;
}
&#13;
<canvas id="canvas" width=200 height=100></canvas>
<select id='align' size="4">
  <option value='left' />left
  <option value='right' />right
  <option value='center' selected="selected" />center
  <option value='justify' />justify
</select>
&#13;
&#13;
&#13;