javascript - PutImageData() 不绘制 ImageData
问题描述
我想制作一个使用这种方法的分形生成器:https ://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/ 这真的很有趣,我想要在正方形和五边形等上尝试。下面代码的结果应该看起来像一个谢尔宾斯基三角形,但不幸的是画布保持空白:/
谢谢你的帮助:)
<!DOCTYPE html>
<html>
<head>
<title>sierpinksi polygons</title>
</head>
<body>
<canvas width="500" height="500" id="canvas"></canvas>
<script>
let canavas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let imgdata = ctx.createImageData(500, 500);
let data = imgdata.data;
let vertices = [{x: 0, y: 0}, {x: 500, y: 0}, {x: 250, y: 433}];
function pixel(x, y) {
data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black
}
function random() {
return vertices[Math.floor(Math.random()*vertices.length)];
}
let point = {x: 0, y: 0};
for (let i = 0; i < 10000; i++) {
let temp = random();
//algorithm to draw sierpinksi triangle pixel by pixel
point.x = point.x + (temp.x - point.x)/2;
point.y = point.y + (temp.y - point.y)/2;
pixel(Math.round(point.x), Math.round(point.y));
}
console.log(imgdata)
ctx.putImageData(imgdata, 0, 0);
</script>
</body>
</html>
解决方案
data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black
不,它没有 - RGBA 值的 A 分量也必须在 0 到 255 的范围内,255 与opacity: 1
CSS 中的含义相匹配。
你在1
这里给你的像素一个 1/255 的不透明度,实际上只有 0.00392156862
您想在255
此处使用以获得全黑像素。
推荐阅读
- android - 问题:违反权限政策
- angular - 改变角度通用的传输状态
- php - 'c' 或 'r' 日期格式在 PHP 中如何工作?
- javascript - 填充图和填充图的区别
- javascript - Chrome 中的 JavaScript 编辑不生效
- bash - 编写路径随更新而更改的可执行文件
- c# - 如何使用 C# 在控制台上打印 UTF-8 字符
- c# - 如何在不支持它的平台上的共享代码库中使用 async/await
- firebase - 我在我的项目中使用 firebase 时遇到问题,我不知道它是来自 react-navigation 还是不同的东西
- python - 使用 pandas Python (pandas.io.parsers.TextFileReader) 从文件中读取数据时出现问题