0

私が求めていることは非常に簡単かもしれませんが、意図した結果を得るのにかなり苦労しています。

形状(この例では正方形ですが、円などの他の形状でも機能するはずです)が別の形状の境界を離れるときにそれ自体を切り取る必要があります。

基本的に、上の画像は私が欲しいもので、下は私が現在持っているものです: http://imgur.com/a/oQkzG

これは globalCompositeOperation で実行できると聞きましたが、必要な結果が得られるソリューションを探しています。

JSFiddle を使用できない場合の現在のコードは次のとおりです。

// Fill the background
ctx.fillStyle = '#0A2E36';
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Fill the parent rect
ctx.fillStyle = '#CCA43B';
ctx.fillRect(100, 100, 150, 150);

// Fill the child rect
ctx.fillStyle = 'red';
ctx.fillRect(200, 200, 70, 70);

// And fill a rect that should not be affected
ctx.fillStyle = 'green';
ctx.fillRect(80, 80, 50, 50);

JSFiddle リンク

4

1 に答える 1

2

オブジェクト間の何らかの関係 (シーン グラフ) が必要なので、ここで作成する必要があります。
あなたの質問から、子要素は親要素によってクリップされて描画される必要があるようです。
(はい、複合操作が助けになる可能性がありますが、それらはクリアな背景に 2 つの図のように描画する場合にのみ便利です。そうしないと、物事がすぐに複雑になり、バック キャンバスを使用する必要がある場合があるため、ここではクリッピングがより簡単になります。)

rect ケースを処理する最も基本的なクラスを以下に示しましたが、構築するのはそれほど難しくないことがわかります。

「シーン」は、黄色と緑色の 2 つの子を持つ背景の Rect から作成されます。そして、黄色の Rect には赤い子があります。

var canvas = document.getElementById('cv');
var ctx = canvas.getContext('2d');

function Rect(fill, x, y, w, h) {
    var childs = [];
    this.draw = function () {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = fill;
        ctx.rect(x, y, w, h);
        ctx.fill();
        ctx.clip();
        for (var i = 0; i < childs.length; i++) {
            childs[i].draw();
        }
        ctx.restore();
    }
    this.addChild = function (child) {
        childs.push(child);
    }
    this.setPos = function (nx, ny) {
        x = nx;
        y = ny;
    }
}

// background
var bgRect = new Rect('#0A2E36', 0, 0, canvas.width, canvas.height);
// One parent rect
var parentRect = new Rect('#CCA43B', 100, 100, 150, 150);
// child rect
var childRect = new Rect('red', 200, 200, 70, 70);
parentRect.addChild(childRect);
//  Another top level rect
var otherRect = new Rect('green', 80, 80, 50, 50);

bgRect.addChild(parentRect);
bgRect.addChild(otherRect);

function drawScene() {
    bgRect.draw();
    drawTitle();
}

drawScene();

window.addEventListener('mousemove', function (e) {
    var rect = canvas.getBoundingClientRect();
    var x = (e.clientX - rect.left);
    var y = (e.clientY - rect.top);
    childRect.setPos(x, y);
    drawScene();
});

function drawTitle() {
    ctx.fillStyle = '#DDF';
    ctx.font = '14px Futura';
    ctx.fillText('Move the mouse around.', 20, 24);
}
<canvas id='cv' width=440 height=440></canvas>

于 2015-10-26T09:40:21.597 に答える