スタートページJavascriptcanvas

clip 画像の切り抜き


画面要素

例0,例1


例1のソースコード

<canvas  id="canvas1" width="200" height="200"
    style="background-color:silver"></canvas>

function rei1() {
    // canvasの設定
    canvas = document.getElementById('canvas1');
    ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, 200, 200);
    // 切り取り領域(円)の設定 これを先に定義すること!
    ctx.arc(70,80,50, 0, Math.PI*2, true);
    ctx.clip();
    // 切り取られる図形(赤い四角)の表示
    ctx.fillStyle = "red";
    ctx.fillRect(50,50,100,100);  // 50+100=150
}

例2

例1の背景に写真を表示

例2のソースコード

<canvas  id="canvas2" width="200" height="200"></canvas>

function rei2() {
    // canvasの設定
    canvas = document.getElementById('canvas2');
    ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, 200, 200);
    // 背景の表示
    var image = new Image();
    image.src = "image/200x200.jpg";
    image.onload = function() {  // 「画像が読み込まれたら」次の処理を行う
                                 // 全ての処理をこのfunction内に記述すること!
        // 背景画像の表示 切り抜きの前に表示!
        ctx.drawImage(image, 0,0, 200,200);
        // 切り取り領域(円)の設定
        ctx.arc(70,80,50, 0, Math.PI*2, true);
        ctx.clip();
        // 切り取られる図形(赤い四角)の表示
        ctx.fillStyle = "red";
        ctx.fillRect(50,50,100,100);
    }
}