2

だから私はいくつかの基本的なキャンバスとを持っていて<input type="color">、色の特定の形の色を変えたいと思ってon changeいます。

これが私のコードです

var colorRect = '#000';

var ball = document.getElementById("canvas");
var ctx = ball.getContext("2d");
var ctx1 = ball.getContext("2d");
ctx1.fillStyle = colorRect;
ctx1.fillRect(0,0,200,200);
ctx1.save();

//Left eye
ctx.fillStyle = '#fff';
ctx.fillRect(50,80,10,10);

//Right eye
ctx.fillStyle = '#fff';
ctx.fillRect(150,80,10,10);

//Nose
ctx.fillStyle = '#fff';
ctx.fillRect(100,110,10,20);

//Mouth

ctx.fillStyle = 'red';
ctx.fillRect(60,150,100,10);

$('#favcolor').on('change',function(){
  colorRect = $(this).val();
  ctx1.fillStyle = $(this).val();
  ctx1.fillRect(0,0,200,200);
});

ここでライブを見ることができます:http: //jsbin.com/inewum/1問題は、目と口が見えなくなったため、すべてが上書きされると思うことです...スタイルを更新したいだけですそれ。

4

3 に答える 3

2

再描画する必要があります。描画ルーチンと色状態変数を作成します。何かを変更したら、新しい色で再描画します。

コンテキストの塗りつぶしスタイルを変更し、その上に長方形を描画するだけです。目と口が消えるのはそのためです。

これに変更して、DEMOを参照してください。

$(function () {

    draw();
    $('#favcolor').on('change', function () {
        colorRect = $(this).val();
        draw();
    });

});

var colorRect = '#000';

function draw() {

    var ball = document.getElementById("canvas");
    var ctx = ball.getContext("2d");
    var ctx1 = ball.getContext("2d");
    ctx1.fillStyle = colorRect;
    ctx1.fillRect(0, 0, 200, 200);
    ctx1.save();

    //Left eye
    ctx.fillStyle = '#fff';
    ctx.fillRect(50, 80, 10, 10);

    //Right eye
    ctx.fillStyle = '#fff';
    ctx.fillRect(150, 80, 10, 10);

    //Nose
    ctx.fillStyle = '#fff';
    ctx.fillRect(100, 110, 10, 20);

    //Mouth

    ctx.fillStyle = 'red';
    ctx.fillRect(60, 150, 100, 10);
}
于 2013-02-22T21:18:58.163 に答える
1

すべての HTML5 キャンバスの図形 (長方形、円、線など) は実体的なオブジェクトではなく、JavaScript DOM オブジェクトのように操作することはできません。そのため、個々の要素のオプションを変更するには、キャンバス イメージ全体を再描画する必要があります。

于 2013-02-22T21:40:36.843 に答える
0

おそらく、SVG の方が必要なものであり、古い HTML と同じように SVG 要素を扱うことができます。

SVG http://jsbin.com/inewum/15/editで行われた例を次に示します

スクリプトは次のように縮小できます。

$('#favcolor').on('change',function(){
    $('.face').css({
      'fill': $(this).val()
    });
});

キャンバスは次のものに置き換えることができます。

<svg height=200 width=200 viewBox='0 0 200 200'>
   <rect width=200 height=200 class="face" />
   <!-- left eye -->
   <rect x=50 y=80 width=10 height=10 fill="white"/>
   <!-- right eye -->
   <rect x=150 y=80 width=10 height=10 fill="white"/>
   <!-- nose -->
   <rect x=100 y=110 width=10 height=20 fill="white"/>
   <!-- mouth -->
   <rect x=60 y=150 width=100 height=10 fill="red"/>
</svg>
于 2013-03-02T15:12:47.557 に答える