aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/canvas_api/tutorial/compositing
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
commit33058f2b292b3a581333bdfb21b8f671898c5060 (patch)
tree51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/web/api/canvas_api/tutorial/compositing
parent8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff)
downloadtranslated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip
initial commit
Diffstat (limited to 'files/zh-cn/web/api/canvas_api/tutorial/compositing')
-rw-r--r--files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html295
-rw-r--r--files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html112
2 files changed, 407 insertions, 0 deletions
diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html
new file mode 100644
index 0000000000..934fa4e2f9
--- /dev/null
+++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.html
@@ -0,0 +1,295 @@
+---
+title: Compositing 示例
+slug: Web/API/Canvas_API/Tutorial/Compositing/Example
+tags:
+ - Canvas
+ - Example
+ - Graphics
+ - HTML
+ - HTML5
+ - Tutorial
+translation_of: Web/API/Canvas_API/Tutorial/Compositing/Example
+---
+<div>{{CanvasSidebar}}</div>
+
+<p>这个案例程序演示了一些<a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.globalCompositeOperation">图像合成操作</a>,其结果如下所示:</p>
+
+<p>{{EmbedLiveSample("合成示例", "100%", 7250)}}</p>
+
+<h2 id="合成示例">合成示例</h2>
+
+<p>下面的代码定义了一些全局变量,可用于程序的其他部分。</p>
+
+<pre class="brush: js">var canvas1 = document.createElement("canvas");
+var canvas2 = document.createElement("canvas");
+var gco = [ 'source-over','source-in','source-out','source-atop',
+            'destination-over','destination-in','destination-out','destination-atop',
+            'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken',
+            'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
+            'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
+          ].reverse();
+var gcoText = [
+'这是默认设置,并在现有画布上下文之上绘制新图形。',
+'新图形只在新图形和目标画布重叠的地方绘制。其他的都是透明的。',
+'在不与现有画布内容重叠的地方绘制新图形。',
+'新图形只在与现有画布内容重叠的地方绘制。',
+'在现有的画布内容后面绘制新的图形。',
+'现有的画布内容保持在新图形和现有画布内容重叠的位置。其他的都是透明的。',
+'现有内容保持在新图形不重叠的地方。',
+'现有的画布只保留与新图形重叠的部分,新的图形是在画布内容后面绘制的。',
+'两个重叠图形的颜色是通过颜色值相加来确定的。',
+'只显示新图形。',
+'图像中,那些重叠和正常绘制之外的其他地方是透明的。',
+'将顶层像素与底层相应像素相乘,结果是一幅更黑暗的图片。',
+'像素被倒转,相乘,再倒转,结果是一幅更明亮的图片。',
+'multiply和screen的结合,原本暗的地方更暗,原本亮的地方更亮。',
+'保留两个图层中最暗的像素。',
+'保留两个图层中最亮的像素。',
+'将底层除以顶层的反置。',
+'将反置的底层除以顶层,然后将结果反过来。',
+'屏幕相乘(A combination of multiply and screen)类似于叠加,但上下图层互换了。',
+'用顶层减去底层或者相反来得到一个正值。',
+'一个柔和版本的强光(hard-light)。纯黑或纯白不会导致纯黑或纯白。',
+'和difference相似,但对比度较低。',
+'保留了底层的亮度(luma)和色度(chroma),同时采用了顶层的色调(hue)。',
+'保留底层的亮度(luma)和色调(hue),同时采用顶层的色度(chroma)。',
+'保留了底层的亮度(luma),同时采用了顶层的色调(hue)和色度(chroma)。',
+'保持底层的色调(hue)和色度(chroma),同时采用顶层的亮度(luma)。'
+          ].reverse();
+var width = 320;
+var height = 340;
+</pre>
+
+<h3 id="主程序">主程序</h3>
+
+<p>当页面加载时,这部分程序会运行,并执行示例代码:</p>
+
+<pre class="brush: js">window.onload = function() {
+    // lum in sRGB
+    var lum = {
+        r: 0.33,
+        g: 0.33,
+        b: 0.33
+    };
+    // resize canvas
+    canvas1.width = width;
+    canvas1.height = height;
+    canvas2.width = width;
+    canvas2.height = height;
+    lightMix()
+    colorSphere();
+    runComposite();
+    return;
+};
+</pre>
+
+<p>这部分代码,,<code>runComposite()</code>,处理了大部分的工作,但需要依赖于许多效用函数来完成复杂的处理工作。</p>
+
+<pre class="brush: js">function createCanvas() {
+    var canvas = document.createElement("canvas");
+    canvas.style.background = "url("+op_8x8.data+")";
+    canvas.style.border = "1px solid #000";
+    canvas.style.margin = "5px";
+    canvas.width = width/2;
+    canvas.height = height/2;
+  return canvas;
+}
+
+function runComposite() {
+    var dl = document.createElement("dl");
+    document.body.appendChild(dl);
+    while(gco.length) {
+        var pop = gco.pop();
+        var dt = document.createElement("dt");
+        dt.textContent = pop;
+        dl.appendChild(dt);
+        var dd = document.createElement("dd");
+        var p = document.createElement("p");
+        p.textContent = gcoText.pop();
+        dd.appendChild(p);
+
+  var canvasToDrawOn = createCanvas();
+   var canvasToDrawFrom = createCanvas();
+   var canvasToDrawResult = createCanvas();
+
+        var ctx = canvasToDrawResult.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = pop;
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = "source-over";
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText(pop, 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawOn.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('existing content', 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawFrom.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('new content', 5, height/2 - 5);
+        ctx.restore();
+
+        dd.appendChild(canvasToDrawOn);
+        dd.appendChild(canvasToDrawFrom);
+        dd.appendChild(canvasToDrawResult);
+
+        dl.appendChild(dd);
+    }
+};
+</pre>
+
+<h3 id="效用函数(Utility_functions)">效用函数(Utility functions)</h3>
+
+<p>程序需要依赖许多效用函数。</p>
+
+<pre class="brush: js">var lightMix = function() {
+    var ctx = canvas2.getContext("2d");
+    ctx.save();
+    ctx.globalCompositeOperation = "lighter";
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(255,0,0,1)";
+    ctx.arc(100, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,0,255,1)";
+    ctx.arc(220, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,255,0,1)";
+    ctx.arc(160, 100, 100, Math.PI*2, 0, false);
+    ctx.fill();
+    ctx.restore();
+    ctx.beginPath();
+    ctx.fillStyle = "#f00";
+    ctx.fillRect(0,0,30,30)
+    ctx.fill();
+};
+</pre>
+
+<pre class="brush: js">var colorSphere = function(element) {
+    var ctx = canvas1.getContext("2d");
+    var width = 360;
+    var halfWidth = width / 2;
+    var rotate = (1 / 360) * Math.PI * 2; // per degree
+    var offset = 0; // scrollbar offset
+    var oleft = -20;
+    var otop = -20;
+    for (var n = 0; n &lt;= 359; n ++) {
+        var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth);
+        var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 });
+        gradient.addColorStop(0, "rgba(0,0,0,0)");
+        gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)");
+        gradient.addColorStop(1, "rgba(255,255,255,1)");
+        ctx.beginPath();
+        ctx.moveTo(oleft + halfWidth, otop);
+        ctx.lineTo(oleft + halfWidth, otop + halfWidth);
+        ctx.lineTo(oleft + halfWidth + 6, otop);
+        ctx.fillStyle = gradient;
+        ctx.fill();
+        ctx.translate(oleft + halfWidth, otop + halfWidth);
+        ctx.rotate(rotate);
+        ctx.translate(-(oleft + halfWidth), -(otop + halfWidth));
+    }
+    ctx.beginPath();
+    ctx.fillStyle = "#00f";
+    ctx.fillRect(15,15,30,30)
+    ctx.fill();
+    return ctx.canvas;
+};
+</pre>
+
+<pre class="brush: js">// HSV (1978) = H: Hue / S: Saturation / V: Value
+Color = {};
+Color.HSV_RGB = function (o) {
+    var H = o.H / 360,
+        S = o.S / 100,
+        V = o.V / 100,
+        R, G, B;
+    var A, B, C, D;
+    if (S == 0) {
+        R = G = B = Math.round(V * 255);
+    } else {
+        if (H &gt;= 1) H = 0;
+        H = 6 * H;
+        D = H - Math.floor(H);
+        A = Math.round(255 * V * (1 - S));
+        B = Math.round(255 * V * (1 - (S * D)));
+        C = Math.round(255 * V * (1 - (S * (1 - D))));
+        V = Math.round(255 * V);
+        switch (Math.floor(H)) {
+            case 0:
+                R = V;
+                G = C;
+                B = A;
+                break;
+            case 1:
+                R = B;
+                G = V;
+                B = A;
+                break;
+            case 2:
+                R = A;
+                G = V;
+                B = C;
+                break;
+            case 3:
+                R = A;
+                G = B;
+                B = V;
+                break;
+            case 4:
+                R = C;
+                G = A;
+                B = V;
+                break;
+            case 5:
+                R = V;
+                G = A;
+                B = B;
+                break;
+        }
+    }
+    return {
+        R: R,
+        G: G,
+        B: B
+    };
+};
+
+var createInterlace = function (size, color1, color2) {
+    var proto = document.createElement("canvas").getContext("2d");
+    proto.canvas.width = size * 2;
+    proto.canvas.height = size * 2;
+    proto.fillStyle = color1; // top-left
+    proto.fillRect(0, 0, size, size);
+    proto.fillStyle = color2; // top-right
+    proto.fillRect(size, 0, size, size);
+    proto.fillStyle = color2; // bottom-left
+    proto.fillRect(0, size, size, size);
+    proto.fillStyle = color1; // bottom-right
+    proto.fillRect(size, size, size, size);
+    var pattern = proto.createPattern(proto.canvas, "repeat");
+    pattern.data = proto.canvas.toDataURL();
+    return pattern;
+};
+
+var op_8x8 = createInterlace(8, "#FFF", "#eee");</pre>
diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html
new file mode 100644
index 0000000000..941b04593e
--- /dev/null
+++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.html
@@ -0,0 +1,112 @@
+---
+title: 组合 Compositing
+slug: Web/API/Canvas_API/Tutorial/Compositing
+tags:
+ - Canvas
+ - Graphics
+ - HTML
+ - HTML5
+ - Intermediate
+ - Totorial
+translation_of: Web/API/Canvas_API/Tutorial/Compositing
+---
+<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}</div>
+
+<div class="summary">
+<p>在<a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations">之前的例子</a>里面,我们总是将一个图形画在另一个之上,对于其他更多的情况,仅仅这样是远远不够的。比如,对合成的图形来说,绘制顺序会有限制。不过,我们可以利用 <code>globalCompositeOperation</code> 属性来改变这种状况。此外, <code>clip</code>属性允许我们隐藏不想看到的部分图形。</p>
+</div>
+
+<h2 id="globalCompositeOperation" name="globalCompositeOperation"><code>globalCompositeOperation</code></h2>
+
+<p>我们不仅可以在已有图形后面再画新图形,还可以用来遮盖指定区域,清除画布中的某些部分(清除区域不仅限于矩形,像{{domxref("CanvasRenderingContext2D.clearRect", "clearRect()")}}方法做的那样)以及更多其他操作。</p>
+
+<dl>
+ <dt>{{domxref("CanvasRenderingContext2D.globalCompositeOperation", "globalCompositeOperation = type")}}</dt>
+ <dd>这个属性设定了在画新图形时采用的遮盖策略,其值是一个标识12种遮盖方式的字符串。</dd>
+</dl>
+
+<p>查看下面<a href="/zh-CN/docs/Web/API/Canvas_API/Tutorial/Compositing/Example">Compositing 示例</a>的代码。</p>
+
+<p>{{EmbedLiveSample("合成示例", 750, 6750, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example")}}</p>
+
+<h2 id="Clipping_paths" name="Clipping_paths">裁切路径</h2>
+
+<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/209/Canvas_clipping_path.png" style="float: right;">裁切路径和普通的 canvas 图形差不多,不同的是它的作用是遮罩,用来隐藏不需要的部分。如右图所示。红边五角星就是裁切路径,所有在路径以外的部分都不会在 canvas 上绘制出来。</p>
+
+<p>如果和上面介绍的 <code>globalCompositeOperation</code> 属性作一比较,它可以实现与 <code>source-in</code> 和 <code>source-atop</code>差不多的效果。最重要的区别是裁切路径不会在 canvas 上绘制东西,而且它永远不受新图形的影响。这些特性使得它在特定区域里绘制图形时相当好用。</p>
+
+<p>在 <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes" title="Web/Guide/HTML/Canvas_tutorial/Drawing_shapes#Drawing_paths">绘制图形</a> 一章中,我只介绍了 <code>stroke</code> 和 <code>fill</code> 方法,这里介绍第三个方法<code>clip</code>。</p>
+
+<dl>
+ <dt>{{domxref("CanvasRenderingContext2D.clip", "clip()")}}</dt>
+ <dd>将当前正在构建的路径转换为当前的裁剪路径。</dd>
+</dl>
+
+<p>我们使用 <code>clip()</code>方法来创建一个新的裁切路径。</p>
+
+<p>默认情况下,canvas 有一个与它自身一样大的裁切路径(也就是没有裁切效果)。</p>
+
+<h3 id="A_clip_example" name="A_clip_example"><code>clip</code> 的例子</h3>
+
+<p>这个例子,我会用一个圆形的裁切路径来限制随机星星的绘制区域。</p>
+
+<pre class="brush: js;highlight[9]">function draw() {
+ var ctx = document.getElementById('canvas').getContext('2d');
+ ctx.fillRect(0,0,150,150);
+ ctx.translate(75,75);
+
+ // Create a circular clipping path
+ ctx.beginPath();
+ ctx.arc(0,0,60,0,Math.PI*2,true);
+ ctx.clip();
+
+ // draw background
+ var lingrad = ctx.createLinearGradient(0,-75,0,75);
+ lingrad.addColorStop(0, '#232256');
+ lingrad.addColorStop(1, '#143778');
+
+ ctx.fillStyle = lingrad;
+ ctx.fillRect(-75,-75,150,150);
+
+ // draw stars
+ for (var j=1;j&lt;50;j++){
+ ctx.save();
+ ctx.fillStyle = '#fff';
+ ctx.translate(75-Math.floor(Math.random()*150),
+ 75-Math.floor(Math.random()*150));
+ drawStar(ctx,Math.floor(Math.random()*4)+2);
+ ctx.restore();
+ }
+
+}
+function drawStar(ctx,r){
+ ctx.save();
+ ctx.beginPath()
+ ctx.moveTo(r,0);
+ for (var i=0;i&lt;9;i++){
+ ctx.rotate(Math.PI/5);
+ if(i%2 == 0) {
+ ctx.lineTo((r/0.525731)*0.200811,0);
+ } else {
+ ctx.lineTo(r,0);
+ }
+ }
+ ctx.closePath();
+ ctx.fill();
+ ctx.restore();
+}
+</pre>
+
+<div class="hidden">
+<pre class="brush: html">&lt;canvas id="canvas" width="150" height="150"&gt;&lt;/canvas&gt;</pre>
+
+<pre class="brush: js">draw();</pre>
+</div>
+
+<p>首先,我画了一个与 canvas 一样大小的黑色方形作为背景,然后移动原点至中心点。然后用 <code>clip</code> 方法创建一个弧形的裁切路径。裁切路径也属于 canvas 状态的一部分,可以被保存起来。如果我们在创建新裁切路径时想保留原来的裁切路径,我们需要做的就是保存一下 canvas 的状态。</p>
+
+<p>裁切路径创建之后所有出现在它里面的东西才会画出来。在画线性渐变时我们就会注意到这点。然后会绘制出50 颗随机位置分布(经过缩放)的星星,当然也只有在裁切路径里面的星星才会绘制出来。</p>
+
+<p>{{EmbedLiveSample("A_clip_example", "180", "180", "https://mdn.mozillademos.org/files/208/Canvas_clip.png")}}</p>
+
+<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}</p>