基于drawImage()
的
文档,我正在尝试绘制到画布的特定部分。然而,目标框之外的区域受到影响,即它们的 alpha 值被归零。
我已经 created a JSFiddle demonstring the issue.
我将左侧的画布(全黄色)复制到右侧的画布,然后使用“destination-atop”将中间的画布绘制到同一画布的中心。您可以看到它应用正确,但同时清除了绘制区域之外的所有内容。 “复制”也是如此。有关详细信息,请参阅Fiddle。
为什么
drawImage()
会影响目的地以外的像素?
定义是:
现有画布仅保留在与新形状重叠的位置。 新形状绘制在画布内容后面。
你想保留一切,使用
source-over
:
这是默认设置并在现有画布内容之上绘制新形状。
const SIZE = 150
const G = 63
let c1 = document.getElementById("c1")
c1.height = c1.width = SIZE
let ctx1 = c1.getContext("2d")
ctx1.fillStyle = "yellow"
ctx1.fillRect(0, 0, SIZE, SIZE)
let c2 = document.getElementById("c2")
c2.height = c2.width = SIZE
let ctx2 = c2.getContext("2d")
let g2= ctx2.createRadialGradient(
SIZE / 2, SIZE / 2,
SIZE / 10,
SIZE / 2, SIZE / 2,
SIZE / 2 - 1)
g2.addColorStop(0.00, `rgba(${G},${G},${G},0.000)`)
g2.addColorStop(0.25, `rgba(${G},${G},${G},0.500)`)
g2.addColorStop(0.50, `rgba(${G},${G},${G},0.750)`)
g2.addColorStop(0.75, `rgba(${G},${G},${G},0.875)`)
g2.addColorStop(1.00, `rgba(${G},${G},${G},1.000)`)
ctx2.fillStyle = g2
ctx2.globalCompositeOperation = "copy"
ctx2.fillRect(0, 0, SIZE, SIZE)
let c3 = document.getElementById("c3")
c3.height = c3.width = SIZE
let ctx3 = c3.getContext("2d")
ctx3.globalCompositeOperation = "source-over";
ctx3.drawImage(c1, 0, 0, SIZE, SIZE)
ctx3.drawImage(c2, SIZE/4, SIZE/4, SIZE/2, SIZE/2)
canvas {
border: 2px solid red;
}
<canvas id="c1"></canvas>
<canvas id="c2"></canvas>
<canvas id="c3"></canvas>