在HTML的Canvas上实现单色渲染图片

2020-04-26 02:51

这里准备了两张图片用作于测试渲染。地图图片是0.png,人物图片是img.png
0.png img.png

这里是一个简单的index.html模板,代码块对应后面的代码内容。

1
2
3
4
5
6
7
8
9
10
11
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-cn">
<head> </head>
<body>
<canvas id="render" width=224px height=235></canvas>
<script>
// 代码块
</script>
</body>
</html>

渲染逻辑如下。首先加载两张图片,确保两张都加载完成了之后在Canvas中将其渲染出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 代码块
let canvas = document.getElementById("render");
let ctx = canvas.getContext("2d");

let imgs = {};
function draw() {
let role = imgs["img.png"];
let map = imgs["0.png"];

ctx.fillStyle = "#ffffff"; //清屏

ctx.fillRect(0, 0, 244, 235);
ctx.drawImage(map, 0, 0);

// 渲染半透明黑色
ctx.globalAlpha = .5;
ctx.globalCompositeOperation = "xor";
ctx.drawImage(role, 5, 60);

ctx.globalAlpha = 1;
ctx.fillStyle = "#000000";
ctx.globalCompositeOperation = "destination-atop";
ctx.fillRect(0, 0, 244, 230);

// 渲染红色
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "xor";
ctx.drawImage(role, 144, 60);

ctx.globalAlpha = 1;
ctx.fillStyle = "#ff0000";
ctx.globalCompositeOperation = "destination-atop";
ctx.fillRect(0, 0, 244, 230);

// 默认的渲染
ctx.fillStyle = "#ffffff";
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(role, 72, 60);
}

var count = 0;
let res = ["0.png", "img.png"];
for (let f of res) {
let img = new Image();
img.onload = function (e) {
imgs[f] = img;
count += 1;
if (count >= res.length)
draw();
}
img.src = f;
}

后记

简单的影子或者人物描边应该是可以用到这个逻辑,实际上我也只是想简单的记录一下罢了。
这里可能会有的问题是在上层改动了transform的时候可能会导致你的ctx.fillRect无法填充正确的区域而导致渲染异常,这可以在ctx.fillRect通过使用ctx.resetTransform来重置后即能正确的渲染了(这个方法在某些浏览器内核没有也可以使用ctx.setTransform(1, 0, 0, 1, 0, 0)来设置,它们的效果是相同)


标签: javascript,

Creative Commons ©fox 2017 - 2018 | Theme based on fzheng.me &